code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
/* * 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 AnalisisLexico; import Repositorio.Variables; import static com.sun.java.accessibility.util.AWTEventMonitor.addKeyListener; import com.sun.org.apache.xalan.internal.lib.ExsltStrings; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.FileNotFoundException; import java.io.IOException; import java.util.LinkedList; import java.util.Map; import java.util.Scanner; /** * * @author ceron */ public class DesCicloMain { public boolean bandera = true, banMate = false; private Variables varia; Operaciones ope = new Operaciones(); LinkedList llist = new LinkedList(); public LinkedList temporal = new LinkedList(); Scanner var = new Scanner(System.in); String supm []={"Pastelito","MedioPastelito","Paleta.Payaso", "Dulce de chocolate", "paletita", "Postre"}; public boolean EvaluaBloques(String obtenLinea, int linea, LinkedList lli)throws FileNotFoundException, IOException{ this.llist = lli; if(Desicion(obtenLinea, linea)){ bandera = true; } else if(DesisionSino(obtenLinea, linea)){ bandera = true; } else if(Impresion(obtenLinea, linea)){ bandera = true; } else if(Ciclo(obtenLinea, linea)){ bandera = true; } else if(Main(obtenLinea, linea)){ bandera = true; } else if(Lectura(obtenLinea, linea)){ bandera = true; } else{ bandera = true; } //varia = null; return bandera; } public boolean Desicion(String obtenLinea, int linea)throws FileNotFoundException, IOException{ String aux[] = obtenLinea.split("\\("); if(aux[0].equals(supm[0])){ if(ope.operacLogic(obtenLinea, linea, supm[0], llist, "N")){ bandera = false; } else { bandera = true; } } else{ bandera = false; } return bandera; } public boolean Main(String obtenLinea, int linea)throws FileNotFoundException, IOException{ String aux[] = obtenLinea.split("\\("); if(aux[0].equals(supm[3])){ if(ope.operacLogic(obtenLinea, linea, supm[3], llist, "N")){ bandera = false; } else { bandera = true; } } else{ bandera = false; } return bandera; } public boolean DesisionSino(String obtenLinea, int linea)throws FileNotFoundException, IOException{ String aux[] = obtenLinea.split("\\("); if(aux[0].equals(supm[1])){ if(ope.operacLogic(obtenLinea, linea, supm[1], llist, "N")){ bandera = false; } else { bandera = true; } } else{ bandera = false; } return bandera; } public boolean Impresion(String obtenLinea, int linea)throws FileNotFoundException, IOException{ String aux[] = obtenLinea.split("\\("); if(aux[0].equals(supm[2])){ if(ope.operacLogic(obtenLinea, linea, supm[2], llist, "N")){ bandera = false; } else { bandera = true; } } else{ bandera = false; } return bandera; } public boolean Ciclo(String obtenLinea, int linea)throws FileNotFoundException, IOException{ String aux[] = obtenLinea.split("\\("); if(aux[0].equals(supm[4])){ if(ope.operacLogic(obtenLinea, linea, supm[4], llist, "N")){ bandera = false; } else { bandera = true; } } else{ bandera = false; } return bandera; } public boolean Lectura(String obtenLinea, int linea){ varia = new Variables(); varia.setIdentificadores(llist); String aux[] = obtenLinea.split("\\("); String variable; boolean ban = true; if(aux[0].equals(supm[5])){ if(aux[1].matches("[a-zA-Z]+[\\)][;]")){ String valor = aux[1].replaceAll("\\);", ""); if(!varia.buscIgualdad(valor)){ varia.ModificaValIdentificador(valor.toLowerCase(), "0", "L"); bandera = true; } else{ System.err.println("Imposible leer "+valor.toUpperCase()+" Error en la linea:"+linea); } } else { bandera = false; } } else{ bandera = false; } return bandera; } public boolean Buscsupm(String verLinea){ boolean ban = true; String borra = verLinea.replaceAll("[\\s]", ""); for (int i = 0; i < 10; i++) { } return ban; } public LinkedList getLLisDesc(){ LinkedList ll = new LinkedList(); ll = this.llist; return ll; } }
DarkCeron/sweetmeat_candy
src/AnalisisLexico/DesCicloMain.java
Java
gpl-2.0
5,455
package ru.svalov.ma.planner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.svalov.ma.data.tempo.PlannedVacation; import ru.svalov.ma.model.CalendarEvent; import ru.svalov.ma.model.CalendarEvents; import ru.svalov.ma.model.Employee; import ru.svalov.ma.model.EventType; import ru.svalov.ma.planner.tempo.VacationService; import ru.svalov.util.JavaTimeUtils; import java.time.LocalDate; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.time.temporal.ChronoUnit.DAYS; public class VacationReplicationService { private static final Logger LOGGER = LoggerFactory.getLogger(VacationReplicationService.class); private CalendarEventsService holidayEventService; private VacationService vacationService; public VacationReplicationService(final CalendarEventsService holidayEventService, final VacationService vacationService) { this.holidayEventService = holidayEventService; this.vacationService = vacationService; } public void replicateVacations(List<Employee> users, LocalDate start, LocalDate end) { List<PlannedVacation> tempoLabors = users.stream().map(Employee::getLogin).map(user -> vacationService.getUserLabors(user, start, end)) .flatMap(List::stream).collect(Collectors.toList()); final CalendarEvents calendarEvents = holidayEventService.get(start, end); Stream.iterate(start, d -> d.plusDays(1)) .limit(start.until(end, DAYS)) .forEach(currentDate -> { final List<CalendarEvent> eventsToRemove = calendarEvents.get(currentDate, EventType.VACATION); eventsToRemove.forEach(ev -> { final long usersCount = users.stream().filter(u -> u.getLogin().equals(ev.getSubject())).count(); if (usersCount > 0) holidayEventService.delete(ev.getId()); }); createNewVacationEvent(users, tempoLabors, currentDate); }); } private void createNewVacationEvent(final List<Employee> users, final List<PlannedVacation> tempoVacs, final LocalDate currentDate) { tempoVacs.stream().filter(vac -> JavaTimeUtils.isInPeriod(currentDate, vac.getStart(), vac.getEnd())).forEach (plannedVacation -> { Optional<Employee> employee = users.stream().filter(user -> user.getLogin().equalsIgnoreCase(plannedVacation.getAssignee().getKey ())).findFirst(); if (!employee.isPresent()) { LOGGER.error("Can't find employee with login: {}", plannedVacation.getAssignee().getKey()); return; } final CalendarEvent event = new CalendarEvent(); event.setDate(currentDate); event.setType(EventType.VACATION); event.setSubject(plannedVacation.getAssignee().getKey()); event.setAttendees(Collections.singletonList(employee.get())); holidayEventService.create(event); }); } }
subzero0x1/SDMA
planner/src/main/java/ru/svalov/ma/planner/VacationReplicationService.java
Java
gpl-2.0
3,248
/* * Classic API Init task create failure * * COPYRIGHT (c) 1989-2008. * On-Line Applications Research Corporation (OAR). * * The license and distribution terms for this file may be * found in the file LICENSE in this distribution or at * http://www.rtems.com/license/LICENSE. * * $Id$ */ /* * Way too much stack space. Should generate a fatal error * on the init task create. */ #define CONFIGURE_HAS_OWN_INIT_TASK_TABLE #define CONFIGURE_INIT_TASK_STACK_SIZE RTEMS_MINIMUM_STACK_SIZE rtems_initialization_tasks_table Initialization_tasks[] = { { rtems_build_name('I', 'N', 'I', ' '), RTEMS_MINIMUM_STACK_SIZE, 1, RTEMS_DEFAULT_ATTRIBUTES, Init, RTEMS_DEFAULT_MODES, 0 } }; #define CONFIGURE_INIT_TASK_TABLE Initialization_tasks #define CONFIGURE_INIT_TASK_TABLE_SIZE \ sizeof(CONFIGURE_INIT_TASK_TABLE) / sizeof(rtems_initialization_tasks_table) #define FATAL_ERROR_TEST_NAME "8" #define FATAL_ERROR_DESCRIPTION "Core workspace too small" #define FATAL_ERROR_EXPECTED_SOURCE INTERNAL_ERROR_CORE #define FATAL_ERROR_EXPECTED_IS_INTERNAL TRUE #define FATAL_ERROR_EXPECTED_ERROR INTERNAL_ERROR_WORKSPACE_ALLOCATION char Workspace[ 256 ] CPU_STRUCTURE_ALIGNMENT; void force_error() { rtems_configuration_set_work_space_start( Workspace ); rtems_configuration_set_work_space_size( sizeof(Workspace) ); rtems_configuration_set_stack_space_size( 0 ); rtems_initialize_data_structures();; /* we will not run this far */ }
daniel-hellstrom/leon-rtems
testsuites/sptests/spfatal08/testcase.h
C
gpl-2.0
1,517
goog.provide('ol.control.FullScreen'); goog.require('goog.asserts'); goog.require('goog.dom'); goog.require('goog.dom.classlist'); goog.require('goog.dom.fullscreen'); goog.require('goog.dom.fullscreen.EventType'); goog.require('goog.events'); goog.require('goog.events.EventType'); goog.require('ol'); goog.require('ol.control.Control'); goog.require('ol.css'); /** * @classdesc * Provides a button that when clicked fills up the full screen with the map. * When in full screen mode, a close button is shown to exit full screen mode. * The [Fullscreen API](http://www.w3.org/TR/fullscreen/) is used to * toggle the map in full screen mode. * * * @constructor * @extends {ol.control.Control} * @param {olx.control.FullScreenOptions=} opt_options Options. * @api stable */ ol.control.FullScreen = function(opt_options) { var options = opt_options ? opt_options : {}; /** * @private * @type {string} */ this.cssClassName_ = options.className ? options.className : 'ol-full-screen'; var label = options.label ? options.label : '\u2922'; /** * @private * @type {Node} */ this.labelNode_ = goog.isString(label) ? document.createTextNode(label) : label; var labelActive = options.labelActive ? options.labelActive : '\u00d7'; /** * @private * @type {Node} */ this.labelActiveNode_ = goog.isString(labelActive) ? document.createTextNode(labelActive) : labelActive; var tipLabel = options.tipLabel ? options.tipLabel : 'Toggle full-screen'; var button = goog.dom.createDom('BUTTON', { 'class': this.cssClassName_ + '-' + goog.dom.fullscreen.isFullScreen(), 'type': 'button', 'title': tipLabel }, this.labelNode_); goog.events.listen(button, goog.events.EventType.CLICK, this.handleClick_, false, this); goog.events.listen(goog.global.document, goog.dom.fullscreen.EventType.CHANGE, this.handleFullScreenChange_, false, this); var cssClasses = this.cssClassName_ + ' ' + ol.css.CLASS_UNSELECTABLE + ' ' + ol.css.CLASS_CONTROL + ' ' + (!goog.dom.fullscreen.isSupported() ? ol.css.CLASS_UNSUPPORTED : ''); var element = goog.dom.createDom('DIV', cssClasses, button); goog.base(this, { element: element, target: options.target }); /** * @private * @type {boolean} */ this.keys_ = options.keys !== undefined ? options.keys : false; }; goog.inherits(ol.control.FullScreen, ol.control.Control); /** * @param {goog.events.BrowserEvent} event The event to handle * @private */ ol.control.FullScreen.prototype.handleClick_ = function(event) { event.preventDefault(); this.handleFullScreen_(); }; /** * @private */ ol.control.FullScreen.prototype.handleFullScreen_ = function() { if (!goog.dom.fullscreen.isSupported()) { return; } var map = this.getMap(); if (!map) { return; } if (goog.dom.fullscreen.isFullScreen()) { goog.dom.fullscreen.exitFullScreen(); } else { var target = map.getTarget(); goog.asserts.assert(target, 'target should be defined'); var element = goog.dom.getElement(target); goog.asserts.assert(element, 'element should be defined'); if (this.keys_) { goog.dom.fullscreen.requestFullScreenWithKeys(element); } else { goog.dom.fullscreen.requestFullScreen(element); } } }; /** * @private */ ol.control.FullScreen.prototype.handleFullScreenChange_ = function() { var opened = this.cssClassName_ + '-true'; var closed = this.cssClassName_ + '-false'; var button = goog.dom.getFirstElementChild(this.element); var map = this.getMap(); if (goog.dom.fullscreen.isFullScreen()) { goog.dom.classlist.swap(button, closed, opened); goog.dom.replaceNode(this.labelActiveNode_, this.labelNode_); } else { goog.dom.classlist.swap(button, opened, closed); goog.dom.replaceNode(this.labelNode_, this.labelActiveNode_); } if (map) { map.updateSize(); } };
tutorielgeo/google-openlayers
ol/ol/control/fullscreencontrol.js
JavaScript
gpl-2.0
3,934
<?php namespace app\controllers; use Yii; use app\models\Expenses; use app\models\ExpensesSearch; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; use yii\filters\AccessControl; use yii\filters\AccessRule; use kartik\widgets\Growl; use app\models\User; /** * ExpensesController implements the CRUD actions for Expenses model. */ class ExpensesController extends Controller { public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), // We will override the default rule config with the new AccessRule class 'ruleConfig' => [ 'class' => AccessRule::className(), ], 'only' => ['create', 'update', 'delete'], 'rules' => [ [ 'actions' => ['create'], 'allow' => true, // Allow users, moderators and admins to create 'roles' => [ User::ROLE_MODERATOR, User::ROLE_ADMIN ], ], [ 'actions' => ['update'], 'allow' => true, // Allow moderators and admins to update 'roles' => [ User::ROLE_MODERATOR, User::ROLE_ADMIN ], ], [ 'actions' => ['delete'], 'allow' => true, // Allow admins to delete 'roles' => [ User::ROLE_ADMIN ], ], ], ], 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['post'], ], ], ]; } /** * Lists all Expenses models. * @return mixed */ public function actionIndex() { $searchModel = new ExpensesSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); } /** * Displays a single Expenses model. * @param integer $id * @return mixed */ public function actionView($id) { return $this->render('view', [ 'model' => $this->findModel($id), ]); } /** * Creates a new Expenses model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new Expenses(); $e_id = ""; //Get the expense id if(isset($_POST['Expenses'])){ $model->attributes = $_POST['Expenses']; $hs = $model->expense_id; //sql to insert bank charges and water charges to other expenses $sql = "INSERT INTO expenses "; } if ($model->load(Yii::$app->request->post()) && $model->save()) { Yii::$app->getSession()->setFlash('success', [ 'type' => Growl::TYPE_SUCCESS, 'duration' => 12000, 'icon' => 'fa fa-users', 'message' => 'Save was successful', 'title' => '', 'positonY' => 'bottom', 'positonX' => 'left' ]); return $this->redirect(['expenses/create']); } else { return $this->render('create', [ 'model' => $model, ]); } } /** * Updates an existing Expenses model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { Yii::$app->getSession()->setFlash('success', [ 'type' => Growl::TYPE_GROWL, 'duration' => 12000, 'icon' => 'fa fa-users', 'message' => 'Update was successful', 'positonY' => 'bottom', 'positonX' => 'left' ]); return $this->redirect(['view', 'id' => $model->expense_id]); } else { return $this->render('update', [ 'model' => $model, ]); } } /** * Deletes an existing Expenses model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id * @return mixed */ public function actionDelete($id) { $this->findModel($id)->delete(); return $this->redirect(['index']); } /** * Finds the Expenses model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return Expenses the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Expenses::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } }
mirr254/paki
controllers/ExpensesController.php
PHP
gpl-2.0
5,396
# MemoryJogger A Class Group Project for EMSE6361
emseGDLC/MemoryJogger
README.md
Markdown
gpl-2.0
50
package de.metas.handlingunits.impl; /* * #%L * de.metas.handlingunits.base * %% * Copyright (C) 2015 metas GmbH * %% * 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/gpl-2.0.html>. * #L% */ import de.metas.handlingunits.IHUTrxQuery; /* package */class HUTrxQuery implements IHUTrxQuery { private int M_HU_Trx_Hdr_ID = -1; private int Exclude_M_HU_Trx_Line_ID = -1; private int Parent_M_HU_Trx_Line_ID = -1; private int Ref_HU_Item_ID = -1; private int AD_Table_ID = -1; private int Record_ID = -1; private int M_HU_ID = -1; @Override public String toString() { return "HUTrxQuery [" + "M_HU_Trx_Hdr_ID=" + M_HU_Trx_Hdr_ID + ", Exclude_M_HU_Trx_Line_ID=" + Exclude_M_HU_Trx_Line_ID + ", Parent_M_HU_Trx_Line_ID=" + Parent_M_HU_Trx_Line_ID + ", Ref_HU_Item_ID=" + Ref_HU_Item_ID + ", AD_Table_ID/Record_ID=" + AD_Table_ID + "/" + Record_ID + "]"; } @Override public int getM_HU_Trx_Hdr_ID() { return M_HU_Trx_Hdr_ID; } @Override public void setM_HU_Trx_Hdr_ID(final int m_HU_Trx_Hdr_ID) { M_HU_Trx_Hdr_ID = m_HU_Trx_Hdr_ID; } @Override public int getExclude_M_HU_Trx_Line_ID() { return Exclude_M_HU_Trx_Line_ID; } @Override public void setExclude_M_HU_Trx_Line_ID(final int exclude_M_HU_Trx_Line_ID) { Exclude_M_HU_Trx_Line_ID = exclude_M_HU_Trx_Line_ID; } @Override public int getParent_M_HU_Trx_Line_ID() { return Parent_M_HU_Trx_Line_ID; } @Override public void setParent_M_HU_Trx_Line_ID(final int parent_M_HU_Trx_Line_ID) { Parent_M_HU_Trx_Line_ID = parent_M_HU_Trx_Line_ID; } @Override public void setM_HU_Item_ID(final int Ref_HU_Item_ID) { this.Ref_HU_Item_ID = Ref_HU_Item_ID; } @Override public int getM_HU_Item_ID() { return Ref_HU_Item_ID; } @Override public int getAD_Table_ID() { return AD_Table_ID; } @Override public void setAD_Table_ID(final int aD_Table_ID) { AD_Table_ID = aD_Table_ID; } @Override public int getRecord_ID() { return Record_ID; } @Override public void setRecord_ID(final int record_ID) { Record_ID = record_ID; } @Override public void setM_HU_ID(int m_hu_ID) { M_HU_ID = m_hu_ID; } @Override public int getM_HU_ID() { return M_HU_ID; } }
klst-com/metasfresh
de.metas.handlingunits.base/src/main/java/de/metas/handlingunits/impl/HUTrxQuery.java
Java
gpl-2.0
2,821
<?php /** * WooThemes Media Library-driven AJAX File Uploader Module (2010-11-05) * * Slightly modified for use in the Options Framework. */ if ( is_admin() ) { // Load additional css and js for image uploads on the Options Framework page $of_page= 'appearance_page_options-framework'; add_action( "admin_print_styles-$of_page", 'optionsframework_mlu_css', 0 ); add_action( "admin_print_scripts-$of_page", 'optionsframework_mlu_js', 0 ); } /** * Sets up a custom post type to attach image to. This allows us to have * individual galleries for different uploaders. */ if ( ! function_exists( 'optionsframework_mlu_init' ) ) { function optionsframework_mlu_init () { register_post_type( 'optionsframework', array( 'labels' => array( 'name' => __( 'Options Framework Internal Container', 'Raptor' ), ), 'public' => true, 'show_ui' => false, 'capability_type' => 'post', 'hierarchical' => false, 'rewrite' => false, 'supports' => array( 'title', 'editor' ), 'query_var' => false, 'can_export' => true, 'show_in_nav_menus' => false ) ); } } /** * Adds the Thickbox CSS file and specific loading and button images to the header * on the pages where this function is called. */ if ( ! function_exists( 'optionsframework_mlu_css' ) ) { function optionsframework_mlu_css () { $_html = ''; $_html .= '<link rel="stylesheet" href="' . site_url() . '/' . WPINC . '/js/thickbox/thickbox.css" type="text/css" media="screen" />' . "\n"; $_html .= '<script type="text/javascript"> var tb_pathToImage = "' . site_url() . '/' . WPINC . '/js/thickbox/loadingAnimation.gif"; var tb_closeImage = "' . site_url() . '/' . WPINC . '/js/thickbox/tb-close.png"; </script>' . "\n"; echo $_html; } } /** * Registers and enqueues (loads) the necessary JavaScript file for working with the * Media Library-driven AJAX File Uploader Module. */ if ( ! function_exists( 'optionsframework_mlu_js' ) ) { function optionsframework_mlu_js () { // Registers custom scripts for the Media Library AJAX uploader. wp_register_script( 'of-medialibrary-uploader', OPTIONS_FRAMEWORK_DIRECTORY .'js/of-medialibrary-uploader.js', array( 'jquery', 'thickbox' ) ); wp_enqueue_script( 'of-medialibrary-uploader' ); wp_enqueue_script( 'media-upload' ); } } /** * Media Uploader Using the WordPress Media Library. * * Parameters: * - string $_id - A token to identify this field (the name). * - string $_value - The value of the field, if present. * - string $_mode - The display mode of the field. * - string $_desc - An optional description of the field. * - int $_postid - An optional post id (used in the meta boxes). * * Dependencies: * - optionsframework_mlu_get_silentpost() */ if ( ! function_exists( 'optionsframework_medialibrary_uploader' ) ) { function optionsframework_medialibrary_uploader( $_id, $_value, $_mode = 'full', $_desc = '', $_postid = 0, $_name = '') { $optionsframework_settings = get_option('optionsframework'); // Gets the unique option id $option_name = $optionsframework_settings['id']; $output = ''; $id = ''; $class = ''; $int = ''; $value = ''; $name = ''; $id = strip_tags( strtolower( $_id ) ); // Change for each field, using a "silent" post. If no post is present, one will be created. $int = optionsframework_mlu_get_silentpost( $id ); // If a value is passed and we don't have a stored value, use the value that's passed through. if ( $_value != '' && $value == '' ) { $value = $_value; } if ($_name != '') { $name = $option_name.'['.$id.']['.$_name.']'; } else { $name = $option_name.'['.$id.']'; } if ( $value ) { $class = ' has-file'; } $output .= '<input id="' . $id . '" class="upload' . $class . '" type="text" name="'.$name.'" value="' . $value . '" />' . "\n"; $output .= '<input id="upload_' . $id . '" class="upload_button button" type="button" value="' . __( 'Upload', 'Raptor' ) . '" rel="' . $int . '" />' . "\n"; if ( $_desc != '' ) { $output .= '<span class="of_metabox_desc">' . $_desc . '</span>' . "\n"; } $output .= '<div class="screenshot" id="' . $id . '_image">' . "\n"; if ( $value != '' ) { $remove = '<a href="javascript:(void);" class="mlu_remove button">Remove</a>'; $image = preg_match( '/(^.*\.jpg|jpeg|png|gif|ico*)/i', $value ); if ( $image ) { $output .= '<img src="' . $value . '" alt="" />'.$remove.''; } else { $parts = explode( "/", $value ); for( $i = 0; $i < sizeof( $parts ); ++$i ) { $title = $parts[$i]; } // No output preview if it's not an image. $output .= ''; // Standard generic output if it's not an image. $title = __( 'View File', 'optionsframework' ); $output .= '<div class="no_image"><span class="file_link"><a href="' . $value . '" target="_blank" rel="external">'.$title.'</a></span>' . $remove . '</div>'; } } $output .= '</div>' . "\n"; return $output; } } /** * Uses "silent" posts in the database to store relationships for images. * This also creates the facility to collect galleries of, for example, logo images. * * Return: $_postid. * * If no "silent" post is present, one will be created with the type "optionsframework" * and the post_name of "of-$_token". * * Example Usage: * optionsframework_mlu_get_silentpost ( 'of_logo' ); */ if ( ! function_exists( 'optionsframework_mlu_get_silentpost' ) ) { function optionsframework_mlu_get_silentpost ( $_token ) { global $wpdb; $_id = 0; // Check if the token is valid against a whitelist. // $_whitelist = array( 'of_logo', 'of_custom_favicon', 'of_ad_top_image' ); // Sanitise the token. $_token = strtolower( str_replace( ' ', '_', $_token ) ); // if ( in_array( $_token, $_whitelist ) ) { if ( $_token ) { // Tell the function what to look for in a post. $_args = array( 'post_type' => 'optionsframework', 'post_name' => 'of-' . $_token, 'post_status' => 'draft', 'comment_status' => 'closed', 'ping_status' => 'closed' ); // Look in the database for a "silent" post that meets our criteria. $query = 'SELECT ID FROM ' . $wpdb->posts . ' WHERE post_parent = 0'; foreach ( $_args as $k => $v ) { $query .= ' AND ' . $k . ' = "' . $v . '"'; } // End FOREACH Loop $query .= ' LIMIT 1'; $_posts = $wpdb->get_row( $query ); // If we've got a post, loop through and get it's ID. if ( count( $_posts ) ) { $_id = $_posts->ID; } else { // If no post is present, insert one. // Prepare some additional data to go with the post insertion. $_words = explode( '_', $_token ); $_title = join( ' ', $_words ); $_title = ucwords( $_title ); $_post_data = array( 'post_title' => $_title ); $_post_data = array_merge( $_post_data, $_args ); $_id = wp_insert_post( $_post_data ); } } return $_id; } } /** * Trigger code inside the Media Library popup. */ if ( ! function_exists( 'optionsframework_mlu_insidepopup' ) ) { function optionsframework_mlu_insidepopup () { if ( isset( $_REQUEST['is_optionsframework'] ) && $_REQUEST['is_optionsframework'] == 'yes' ) { add_action( 'admin_head', 'optionsframework_mlu_js_popup' ); add_filter( 'media_upload_tabs', 'optionsframework_mlu_modify_tabs' ); } } } if ( ! function_exists( 'optionsframework_mlu_js_popup' ) ) { function optionsframework_mlu_js_popup () { $_of_title = $_REQUEST['of_title']; if ( ! $_of_title ) { $_of_title = 'file'; } // End IF Statement ?> <script type="text/javascript"> <!-- jQuery(function($) { jQuery.noConflict(); // Change the title of each tab to use the custom title text instead of "Media File". $( 'h3.media-title' ).each ( function () { var current_title = $( this ).html(); var new_title = current_title.replace( 'media file', '<?php echo $_of_title; ?>' ); $( this ).html( new_title ); } ); // Change the text of the "Insert into Post" buttons to read "Use this File". $( '.savesend input.button[value*="Insert into Post"], .media-item #go_button' ).attr( 'value', 'Use this File' ); // Hide the "Insert Gallery" settings box on the "Gallery" tab. $( 'div#gallery-settings' ).hide(); // Preserve the "is_optionsframework" parameter on the "delete" confirmation button. $( '.savesend a.del-link' ).click ( function () { var continueButton = $( this ).next( '.del-attachment' ).children( 'a.button[id*="del"]' ); var continueHref = continueButton.attr( 'href' ); continueHref = continueHref + '&is_optionsframework=yes'; continueButton.attr( 'href', continueHref ); } ); }); --> </script> <?php } } /** * Triggered inside the Media Library popup to modify the title of the "Gallery" tab. */ if ( ! function_exists( 'optionsframework_mlu_modify_tabs' ) ) { function optionsframework_mlu_modify_tabs ( $tabs ) { $tabs['gallery'] = str_replace( __( 'Gallery', 'optionsframework' ), __( 'Previously Uploaded', 'optionsframework' ), $tabs['gallery'] ); return $tabs; } }
doloreel/smh-wp
wp-content/themes/raptor/admin/options-medialibrary-uploader.php
PHP
gpl-2.0
9,395
#ifndef __SINAIS_H_ #define __SINAIS_H_ #include <signal.h> #include <sys/types.h> #include <dirent.h> void interrupcao_clean(); void interrupcao_usr1(); void interrupcao_pipe(); void carrega_config(); #endif
ric2b/Server_PSis
Server Code and Files/sinais.h
C
gpl-2.0
212
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18408 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Form1.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Form1.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
phuhungct1996/QLBH
QLBH/frWineCT/wineCT/Properties/Resources.Designer.cs
C#
gpl-2.0
2,838
<?php return array( 'title'=>'Opciones del servidor SMTP', 'php_mail'=>'&#191;Usar la funci&#243;n de PHP mail()?', 'php_mail_desc'=>'Utiliza esta opci&#243;n si el servidor SMTP no te funciona, la configuraci&#243; del servidor no permite utilizar directamente SMTP o no dispones de servidor SMTP. NOTE: Si seleccionas esta opci&#243;n, no es necesario modificar ninguna de las otras opciones, ser&#225;n ignoradas.', 'server'=>'Servidor SMTP', 'server_desc'=>'La direcci&#243;n IP o el nombre del host/dominio del servidor a trav&#233;s del cual se envia el email via SMTP.', 'port'=>'Puerto', 'port_desc'=>'El puerto a trav&#233;s del cual el servidor SMTP esta escuchando las conexiones SMTP. Si conoce cual es, deje el puerto por defecto (puerto 25).', 'auth'=>'M&#233;todo de autentificaci&#243;n', 'auth_desc'=>'Aqu&#237; puede especificar que tipo de autentificaci&#243;n requiere su servidor SMTP (si es necesaria). Por favor, consulte esta informaci&#243;n al admnistrador de su servidor de correo.', 'auth_none'=>'Sin autentifiacaci&#243;n', 'auth_plain'=>'PLAIN', 'auth_login'=>'LOGIN', 'username'=>'Usuario SMTP', 'username_desc'=>'El usuario que va a usar cuando conecte a un servidor SMTP que requiera autentifiacaci&#243;n', 'password'=>'Contrase&#241;a SMTP', 'password_desc'=>'La contraseña que tiene que usar cuando conecte a un servidor SMTP que requiera autentifiacaci&#243;n', 'from_address'=>'Direcci&#243;n de env&#237;o', 'from_address_desc'=>'Direcci&#243; de email que se usa para comunicarse con el servidor SMTP. Esto es importante para servidores SMTP que restringen el acceso a ciertas direcciones de email.', ); ?>
exponentcms/exponent-cms-1
subsystems/lang/es_ES/conf/extensions/smtp.structure.php
PHP
gpl-2.0
1,682
/* Copyright (c) 2009 Constantin Berzan <exit3219@gmail.com> This library 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 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef AKONADI_TRANSPORTRESOURCEBASE_P_H #define AKONADI_TRANSPORTRESOURCEBASE_P_H #include "transportresourcebase.h" #include <QtCore/QObject> class Akonadi__TransportAdaptor; namespace Akonadi { class TransportResourceBase; /** @internal This class hosts the D-Bus adaptor for TransportResourceBase. */ class TransportResourceBasePrivate : public QObject { Q_OBJECT public: explicit TransportResourceBasePrivate(TransportResourceBase *qq); Q_SIGNALS: /** * Emitted when an item has been sent. * @param item The id of the item that was sent. * @param result The result of the sending operation. * @param message An optional textual explanation of the result. * @since 4.4 */ void transportResult(qlonglong item, int result, const QString &message); // D-Bus signal private Q_SLOTS: void fetchResult(KJob *); private: friend class TransportResourceBase; friend class ::Akonadi__TransportAdaptor; void send(Akonadi::Item::Id message); // D-Bus call TransportResourceBase *const q; }; } // namespace Akonadi #endif // AKONADI_TRANSPORTRESOURCEBASE_P_H
kolab-groupware/kdepimlibs
akonadi/transportresourcebase_p.h
C
gpl-2.0
1,988
<?php /* * * * * * * * * * * * * * * * * * * * * Shows the author links * * * * * * * * * * * * * * * * * * * */ class GPAISRFilter { /** * @since 0.6 */ function __construct() { $options = get_option( 'gpaisr' ); if( isset( $options['replacement'] ) && $options['replacement'] == 1 ) { add_filter( 'author_link', array( $this, 'author_link_filter' ), 0, 3 ); } else { add_filter( 'the_content', array( $this, 'author_link_in_content' ), 15 ); } } /** * Just replaces the link with the google+ url * * @param $link * @param $author_id * @param $author_nicename * * @since 0.6 * * @return string */ function author_link_filter( $link, $author_id, $author_nicename ) { $gplus_author_link = get_the_author_meta( 'gplus_link', $author_id ); if( ! empty( $gplus_author_link ) ) return $gplus_author_link . '?rel=author'; return $link; } /** * Writes the Google+-URL right after the Content * * @param $content * * @since 0.6 * * @return string */ function author_link_in_content( $content ) { // load the options from the settings page $options = get_option( 'gpaisr' ); // is this the feed? if yes, should we display the link? if( ! isset( $options['in_feed'] ) ) $options['in_feed'] = 0; if( is_feed() && $options['in_feed'] != 1 ) return $content; // what's the author id? $authorId = get_the_author_meta( 'ID' ); // find the link $gplus_author_link = get_the_author_meta( 'gplus_link', $authorId ); if( ! empty( $gplus_author_link ) ) $gplus_author_link = $gplus_author_link . '?rel=author'; // open in a new window? $newWindow = ''; if( isset( $options['new_window'] ) && $options['new_window'] == 1 ) $newWindow = 'target="_blank"'; // show or hide? $showHide = ''; if( isset( $options['hide'] ) && $options['hide'] == 1 ) { $showHide = 'style="display:none;"'; } // is there a linktext? $linktext = 'Google+'; if( ! empty( $options['link_text'] ) ) $linktext = $options['link_text']; return $content .= '<a rel="author" href="' . $gplus_author_link . '" ' . $newWindow . ' ' . $showHide . '>' . $linktext . '</a>'; } }
yondri/newyorkando
wp-content/plugins/google-author-information-in-search-results-wordpress-plugin/class.filter.php
PHP
gpl-2.0
2,158
<?php /* +--------------------------------------------------------------------+ | CiviCRM version 1.8 | +--------------------------------------------------------------------+ | Copyright CiviCRM LLC (c) 2004-2007 | +--------------------------------------------------------------------+ | This file is a part of CiviCRM. | | | | CiviCRM is free software; you can copy, modify, and distribute it | | under the terms of the Affero General Public License Version 1, | | March 2002. | | | | 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 Affero General Public License for more details. | | | | You should have received a copy of the Affero General Public | | License along with this program; if not, contact CiviCRM LLC | | at info[AT]civicrm[DOT]org. If you have questions about the | | 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-2007 * $Id$ * */ require_once 'CRM/Core/Session.php'; require_once 'CRM/Core/DAO/UFMatch.php'; /** * The basic class that interfaces with the external user framework */ class CRM_Core_BAO_UFMatch extends CRM_Core_DAO_UFMatch { /** * Given a UF user object, make sure there is a contact * object for this user. If the user has new values, we need * to update the CRM DB with the new values * * @param Object $user the drupal user object * @param boolean $update has the user object been edited * @param $uf * * @return void * @access public * @static */ static function synchronize( &$user, $update, $uf, $ctype ) { $session =& CRM_Core_Session::singleton( ); if ( ! is_object( $session ) ) { CRM_Core_Error::fatal( 'wow, session is not an object?' ); return; } if ( $uf == 'Drupal' ) { $key = 'uid'; $mail = 'mail'; } else if ( $uf == 'Joomla' ) { $key = 'id'; $mail = 'email'; } else if ( $uf == 'Standalone' ) { // There is no CMS to synchronize with in the standalone version, // so just return. return; } else { CRM_Core_Error::statusBounce(ts('Please set the user framework variable')); } // have we already processed this user, if so early // return. $userID = $session->get( 'userID' ); $ufID = $session->get( 'ufID' ); if ( ! $update && $ufID == $user->$key ) { return; } // reset the session if we are a different user if ( $ufID && $ufID != $user->$key ) { $session->reset( ); } // make sure we load the joomla object to get valid information if ( $uf == 'Joomla' ) { $user->load( ); } // if the id of the object is zero (true for anon users in drupal) // return early if ( $user->$key == 0 ) { return; } $ufmatch =& self::synchronizeUFMatch( $user, $user->$key, $user->$mail, $uf, null, $ctype ); if ( ! $ufmatch ) { return; } $session->set( 'ufID' , $ufmatch->uf_id ); $session->set( 'userID' , $ufmatch->contact_id ); $session->set( 'domainID', $ufmatch->domain_id ); $session->set( 'ufEmail' , $ufmatch->email ); if ( $update ) { // the only information we care about is email, so lets check that if ( $user->$mail != $ufmatch->email ) { // email has changed, so we need to change all our primary email also $ufmatch->email = $user->$mail; $ufmatch->save( ); $query = " UPDATE civicrm_contact LEFT JOIN civicrm_location ON ( civicrm_location.entity_table = 'civicrm_contact' AND civicrm_contact.id = civicrm_location.entity_id AND civicrm_location.is_primary = 1 ) LEFT JOIN civicrm_email ON ( civicrm_location.id = civicrm_email.location_id AND civicrm_email.is_primary = 1 ) SET civicrm_email.email = %1 WHERE civicrm_contact.id = %2 "; $p = array( 1 => array( $user->$mail , 'String' ), 2 => array( $ufmatch->contact_id, 'Integer' ) ); CRM_Core_DAO::executeQuery( $query, $p ); } } } /** * Synchronize the object with the UF Match entry. Can be called stand-alone from * the drupalUsers script * * @param Object $user the drupal user object * @param string $userKey the id of the user from the uf object * @param string $mail the email address of the user * @param string $uf the name of the user framework * @param integer $status returns the status if user created or already exits (used for CMS sync) * * @return the ufmatch object that was found or created * @access public * @static */ static function &synchronizeUFMatch( &$user, $userKey, $mail, $uf, $status = null, $ctype = null ) { // validate that mail is a valid email address. hopefully there is // not too many conflicting emails between the CMS and CiviCRM require_once 'CRM/Utils/Rule.php'; if ( ! CRM_Utils_Rule::email( $mail ) ) { return $status ? null : false; } $newContact = false; // make sure that a contact id exists for this user id $ufmatch =& new CRM_Core_DAO_UFMatch( ); $ufmatch->uf_id = $userKey; $ufmatch->domain_id = CRM_Core_Config::domainID( ); if ( ! $ufmatch->find( true ) ) { require_once 'CRM/Contact/BAO/Contact.php'; $dao =& CRM_Contact_BAO_Contact::matchContactOnEmail( $mail, $ctype ); if ( $dao ) { $ufmatch->contact_id = $dao->contact_id; $ufmatch->domain_id = $dao->domain_id ; $ufmatch->email = $mail; } else { require_once 'CRM/Core/BAO/LocationType.php'; $locationType =& CRM_Core_BAO_LocationType::getDefault( ); $params = array( 'email' => $mail, 'location_type' => $locationType->name ); if ( $ctype == 'Organization' ) { $params['organization_name'] = $mail; } else if ( $ctype == 'Household' ) { $params['household_name'] = $mail; } if ( ! $ctype ) { $ctype = "Individual"; } $params['contact_type'] = $ctype; // extract first / middle / last name // for joomla if ( $uf == 'Joomla' && $user->name ) { $name = trim( $user->name ); $names = explode( ' ', $user->name ); if ( count( $names ) == 1 ) { $params['first_name'] = $names[0]; } else if ( count( $names ) == 2 ) { $params['first_name'] = $names[0]; $params['last_name' ] = $names[1]; } else { $params['first_name' ] = $names[0]; $params['middle_name'] = $names[1]; $params['last_name' ] = $names[2]; } } require_once 'api/Contact.php'; $contact =& crm_create_contact( $params, $ctype, false ); if ( is_a( $contact, 'CRM_Core_Error' ) ) { CRM_Core_Error::debug( 'error', $contact ); exit(1); } $ufmatch->contact_id = $contact->id; $ufmatch->domain_id = $contact->domain_id ; $ufmatch->email = $mail; } $ufmatch->save( ); $newContact = true; } if ( $status ) { return $newContact; } else { return $ufmatch; } } /** * update the email in the user object * * @param int $contactId id of the contact to delete * * @return void * @access public * @static */ static function updateUFEmail( $contactId ) { $email = CRM_Contact_BAO_Contact::getPrimaryEmail( $contactId ); if ( ! $email ) { return; } $ufmatch =& new CRM_Core_DAO_UFMatch( ); $ufmatch->contact_id = $contactId; if ( ! $ufmatch->find( true ) || $ufmatch->email == $email ) { // if object does not exist or the email has not changed return; } // save the updated ufmatch object $ufmatch->email = $email; $ufmatch->save( ); $config =& CRM_Core_Config::singleton( ); if ( $config->userFramework == 'Drupal' ) { $user = user_load( array( 'uid' => $ufmatch->uf_id ) ); user_save( $user, array( 'mail' => $email ) ); $user = user_load( array( 'uid' => $ufmatch->uf_id ) ); } } /** * Update the email value for the contact and user profile * * @param $contactId Int Contact ID of the user * @param $email String email to be modified for the user * * @return void * @access public * @static */ static function updateContactEmail($contactId, $emailAddress) { $ufmatch =& new CRM_Core_DAO_UFMatch( ); $ufmatch->contact_id = $contactId; if ( $ufmatch->find( true ) ) { // Save the email in UF Match table $ufmatch->email = $emailAddress; $ufmatch->save( ); //check if the primary email for the contact exists //$contactDetails[1] - email //$contactDetails[3] - location id $contactDetails = CRM_Contact_BAO_Contact::getEmailDetails($contactId); if (trim($contactDetails[1])) { //update if record is found $query ="UPDATE civicrm_contact, civicrm_location,civicrm_email SET email = %1 WHERE civicrm_location.entity_table = 'civicrm_contact' AND civicrm_contact.id = civicrm_location.entity_id AND civicrm_location.is_primary = 1 AND civicrm_location.id = civicrm_email.location_id AND civicrm_email.is_primary = 1 AND civicrm_contact.id = %2"; $p = array( 1 => array( $emailAddress, 'String' ), 2 => array( $contactId , 'Integer' ) ); $dao =& CRM_Core_DAO::executeQuery( $query, $p ); } else { //else insert a new email record $email =& new CRM_Core_DAO_Email(); $email->location_id = $contactDetails[3]; $email->is_primary = 1; $email->email = $emailAddress; $email->save( ); $emailID = $email->id; } require_once 'CRM/Core/BAO/Log.php'; // we dont know the email id, so we use the location id CRM_Core_BAO_Log::register( $contactId, 'civicrm_location', $contactDetails[3] ); } } /** * Delete the object records that are associated with this contact * * @param int $contactID id of the contact to delete * * @return void * @access public * @static */ static function deleteContact( $contactID ) { $ufmatch =& new CRM_Core_DAO_UFMatch( ); $ufmatch->contact_id = $contactID; $ufmatch->delete( ); } /** * Delete the object records that are associated with this cms user * * @param int $ufID id of the user to delete * * @return void * @access public * @static */ static function deleteUser( $ufID ) { $ufmatch =& new CRM_Core_DAO_UFMatch( ); $ufmatch->uf_id = $ufID; $ufmatch->delete( ); } /** * get the contact_id given a uf_id * * @param int $ufID Id of UF for which related contact_id is required * * @return int contact_id on success, null otherwise * @access public * @static */ static function getContactId( $ufID ) { if (!isset($ufID)) { return null; } $ufmatch =& new CRM_Core_DAO_UFMatch( ); $ufmatch->uf_id = $ufID; if ( $ufmatch->find( true ) ) { return $ufmatch->contact_id; } return null; } /** * get the uf_id given a contact_id * * @param int $contactID ID of the contact for which related uf_id is required * * @return int uf_id of the given contact_id on success, null otherwise * @access public * @static */ static function getUFId( $contactID ) { if (!isset($contactID)) { return null; } $ufmatch =& new CRM_Core_DAO_UFMatch( ); $ufmatch->contact_id = $contactID; if ( $ufmatch->find( true ) ) { return $ufmatch->uf_id; } return null; } /** * get the list of contact_id * * * @return int contact_id on success, null otherwise * @access public * @static */ static function getContactIDs() { $id = array(); $dao =& new CRM_Core_DAO_UFMatch(); $dao->find(); while ($dao->fetch()) { $id[] = $dao->contact_id; } return $id; } } ?>
zakiya/Peoples-History
sites/all/modules/civicrm/CRM/Core/BAO/UFMatch.php
PHP
gpl-2.0
14,673
/* * s390-tools/zipl/src/job.c * Functions and data structures representing the actual 'job' that the * user wants us to execute. * * Copyright IBM Corp. 2001, 2009. * * Author(s): Carsten Otte <cotte@de.ibm.com> * Peter Oberparleiter <Peter.Oberparleiter@de.ibm.com> */ #include "job.h" #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <getopt.h> #include <string.h> #include <errno.h> #include "error.h" #include "misc.h" #include "scan.h" /* Command line options */ static struct option options[] = { { "config", required_argument, NULL, 'c'}, { "target", required_argument, NULL, 't'}, { "targetbase", required_argument, NULL, 0xaa}, { "targettype", required_argument, NULL, 0xab}, { "targetgeometry", required_argument, NULL, 0xac}, { "targetblocksize", required_argument, NULL, 0xad}, { "targetoffset", required_argument, NULL, 0xae}, { "image", required_argument, NULL, 'i'}, { "ramdisk", required_argument, NULL, 'r'}, { "parmfile", required_argument, NULL, 'p'}, { "parameters", required_argument, NULL, 'P'}, { "dumpto", required_argument, NULL, 'd'}, { "dumptofs", required_argument, NULL, 'D'}, { "mvdump", required_argument, NULL, 'M'}, { "segment", required_argument, NULL, 's'}, { "menu", required_argument, NULL, 'm'}, { "help", no_argument, NULL, 'h'}, { "noninteractive", no_argument, NULL, 'n'}, { "version", no_argument, NULL, 'v'}, { "verbose", no_argument, NULL, 'V'}, { "add-files", no_argument, NULL, 'a'}, { "tape", required_argument, NULL, 'T'}, { "dry-run", no_argument, NULL, '0'}, { "force", no_argument, NULL, 'f'}, { "kdump", required_argument, NULL, 'k'}, { NULL, 0, NULL, 0 } }; /* Command line option abbreviations */ static const char option_string[] = "-c:t:i:r:p:P:d:D:M:s:m:hHnVvaT:fk:"; struct command_line { char* data[SCAN_KEYWORD_NUM]; char* config; char* menu; char* section; int help; int noninteractive; int version; int verbose; int add_files; int dry_run; int force; enum scan_section_type type; }; static int store_option(struct command_line* cmdline, enum scan_keyword_id keyword, char* value) { if (cmdline->data[(int) keyword] != NULL) { error_reason("Option '%s' specified more than once", scan_keyword_name(keyword)); return -1; } cmdline->data[(int) keyword] = value; return 0; } static int get_command_line(int argc, char* argv[], struct command_line* line) { struct command_line cmdline; int is_keyword; int opt; int rc; int i; memset((void *) &cmdline, 0, sizeof(struct command_line)); cmdline.type = section_invalid; is_keyword = 0; /* Process options */ do { opt = getopt_long(argc, argv, option_string, options, NULL); rc = 0; switch (opt) { case 'd': is_keyword = 1; rc = store_option(&cmdline, scan_keyword_dumpto, optarg); break; case 'D': error_reason("dumptofs has been deprecated, use " "--dump instead"); rc = -1; break; case 'M': is_keyword = 1; rc = store_option(&cmdline, scan_keyword_mvdump, optarg); #ifndef __s390x__ error_reason("Option '%s' not supported on 31-bit", scan_keyword_name(scan_keyword_mvdump)); rc = -1; #endif break; case 'i': is_keyword = 1; rc = store_option(&cmdline, scan_keyword_image, optarg); break; case 'P': rc = store_option(&cmdline, scan_keyword_parameters, optarg); break; case 'p': is_keyword = 1; rc = store_option(&cmdline, scan_keyword_parmfile, optarg); break; case 'r': is_keyword = 1; rc = store_option(&cmdline, scan_keyword_ramdisk, optarg); break; case 's': is_keyword = 1; rc = store_option(&cmdline, scan_keyword_segment, optarg); break; case 't': is_keyword = 1; rc = store_option(&cmdline, scan_keyword_target, optarg); break; case 0xaa: is_keyword = 1; rc = store_option(&cmdline, scan_keyword_targetbase, optarg); break; case 0xab: is_keyword = 1; rc = store_option(&cmdline, scan_keyword_targettype, optarg); break; case 0xac: is_keyword = 1; rc = store_option(&cmdline, scan_keyword_targetgeometry, optarg); break; case 0xad: is_keyword = 1; rc = store_option(&cmdline, scan_keyword_targetblocksize, optarg); break; case 0xae: is_keyword = 1; rc = store_option(&cmdline, scan_keyword_targetoffset, optarg); break; case 'T': is_keyword = 1; rc = store_option(&cmdline, scan_keyword_tape, optarg); break; case 'k': is_keyword = 1; rc = store_option(&cmdline, scan_keyword_kdump, optarg); break; case 'c': if (cmdline.config != NULL) { error_reason("Option 'config' specified more " "than once"); rc = -1; } else cmdline.config = optarg; break; case 'm': if (cmdline.menu != NULL) { error_reason("Option 'menu' specified more " "than once"); rc = -1; } else cmdline.menu = optarg; break; case 'h': cmdline.help = 1; break; case 'n': cmdline.noninteractive = 1; break; case 'v': cmdline.version = 1; break; case 'V': cmdline.verbose = 1; break; case 'a': cmdline.add_files = 1; break; case '0': cmdline.dry_run = 1; break; case 'f': cmdline.force = 1; break; case 1: /* Non-option is interpreted as section name */ if (cmdline.section != NULL) { error_reason("More than one section " "specified on command line"); rc = -1; } else cmdline.section = optarg; break; case -1: /* End of options string */ break; default: fprintf(stderr, "Try 'zipl --help' for " "more information.\n"); exit(1); } if (rc) return rc; } while (opt != -1); /* Check command line options */ if (cmdline.help || cmdline.version) { /* Always accept --help and --version */ } else if ((cmdline.menu != NULL) || (cmdline.section != NULL)) { /* Config file mode */ if ((cmdline.menu != NULL) && (cmdline.section != NULL)) { error_reason("Option 'menu' cannot be used when " "specifying a configuration section"); return -1; } /* Make sure no other keyword option was specified */ for (i=0; i < SCAN_KEYWORD_NUM; i++) { /* Allow '--parameters' when specifying a section */ if ((i == (int) scan_keyword_parameters) && (cmdline.menu == NULL)) continue; if (cmdline.data[i] != NULL) { if (cmdline.menu != NULL) { error_reason("Only one of options " "'menu' and '%s' allowed", scan_keyword_name( (enum scan_keyword_id) i)); } else { error_reason("Option '%s' cannot be " "used when specifying " "a configuration section", scan_keyword_name( (enum scan_keyword_id) i)); } return -1; } } } else if (is_keyword) { /* Command line mode */ rc = scan_check_section_data(cmdline.data, NULL, NULL, 0, &cmdline.type); if (rc) { if (cmdline.type == section_invalid) { error_reason("Need one of options 'image', " "'segment','dumpto', 'dumptofs', " "'mvdump' or 'menu'"); } return rc; } rc = scan_check_target_data(cmdline.data, NULL); if (rc) return rc; } *line = cmdline; return 0; } static void free_target_data(struct job_target_data* data) { if (data->targetbase != NULL) free(data->targetbase); } static void free_ipl_data(struct job_ipl_data* data) { if (data->image != NULL) free(data->image); if (data->parmline != NULL) free(data->parmline); if (data->ramdisk != NULL) free(data->ramdisk); } static void free_ipl_tape_data(struct job_ipl_tape_data* data) { if (data->device != NULL) free(data->device); if (data->image != NULL) free(data->image); if (data->parmline != NULL) free(data->parmline); if (data->ramdisk != NULL) free(data->ramdisk); } static void free_segment_data(struct job_segment_data* data) { if (data->segment != NULL) free(data->segment); } static void free_dump_data(struct job_dump_data* data) { if (data->device != NULL) free(data->device); if (data->image != NULL) free(data->image); if (data->parmline != NULL) free(data->parmline); if (data->ramdisk != NULL) free(data->ramdisk); } static void free_menu_data(struct job_menu_data* data) { int i; if (data->entry != NULL) { for (i=0; i < data->num; i++) { if (data->entry[i].name != NULL) free(data->entry[i].name); switch (data->entry[i].id) { case job_ipl: free_ipl_data(&data->entry[i].data.ipl); break; case job_dump_partition: free_dump_data( &data->entry[i].data.dump); break; default: break; } } free(data->entry); } } void free_mvdump_data(struct job_mvdump_data* data) { int i; if (data->device_list != NULL) free(data->device_list); for (i = 0; i < data->device_count; i++) if (data->device[i] != NULL) free(data->device[i]); } void job_free(struct job_data* job) { if (job->target.bootmap_dir != NULL) free(job->target.bootmap_dir); free_target_data(&job->target); if (job->name != NULL) free(job->name); switch (job->id) { case job_ipl: free_ipl_data(&job->data.ipl); break; case job_menu: free_menu_data(&job->data.menu); break; case job_segment: free_segment_data(&job->data.segment); break; case job_dump_partition: free_dump_data(&job->data.dump); break; case job_mvdump: free_mvdump_data(&job->data.mvdump); break; case job_ipl_tape: free_ipl_tape_data(&job->data.ipl_tape); break; default: break; } free(job); } struct component_loc { char *name; address_t *addrp; size_t size; off_t align; }; static int set_cl_element(struct component_loc *cl, char *name, char *filename, address_t *addrp, size_t size, off_t off, off_t align) { struct stat stats; cl->name = name; cl->addrp = addrp; cl->align = align; if (size != 0) { /* The loader works on blocks, so alignment is required */ cl->size = ALIGN(size, MAXIMUM_PHYSICAL_BLOCKSIZE); return 0; } /* Get size */ if (stat(filename, &stats)) { error_reason(strerror(errno)); error_text("Could not get information for file '%s'", filename); return -1; } cl->size = ALIGN(stats.st_size - off, MAXIMUM_PHYSICAL_BLOCKSIZE); return 0; } static void sort_cl_array(struct component_loc* cl, int elements) { int i, j, min; struct component_loc swap; /* Selection sort keeping sequence */ for (i = 0; i < elements - 1; i++) { min = i; for (j = i + 1; j < elements; j++) { if (*(cl[j].addrp) == UNSPECIFIED_ADDRESS) continue; if ((*(cl[min].addrp) == UNSPECIFIED_ADDRESS) || (*(cl[j].addrp) < *(cl[min].addrp))) min = j; } if (i != min) { swap = cl[i]; cl[i] = cl[min]; for (j = min; j > i + 1; j--) cl[j] = cl[j - 1]; cl[i + 1] = swap; } } } static int get_ipl_components(struct job_ipl_data *ipl, struct component_loc **clp, int *nump) { struct component_loc *cl; int num; int rc; /* Get memory for image, parmline, ramdisk */ cl = misc_calloc(3, sizeof(struct component_loc)); if (cl == NULL) return -1; /* Fill in component data */ num = 0; rc = set_cl_element(&cl[num++], "kernel image", ipl->image, &ipl->image_addr, 0, 0x10000, MAXIMUM_PHYSICAL_BLOCKSIZE); if (rc) goto error; if (ipl->parmline) { rc = set_cl_element(&cl[num++], "parmline", NULL, &ipl->parm_addr, MAXIMUM_PARMLINE_SIZE, 0, MAXIMUM_PHYSICAL_BLOCKSIZE); if (rc) goto error; } if (ipl->ramdisk) { rc = set_cl_element(&cl[num++], "initial ramdisk", ipl->ramdisk, &ipl->ramdisk_addr, 0, 0, 0x10000); if (rc) goto error; } *clp = cl; *nump = num; return 0; error: free(cl); return rc; } static int get_dump_components(struct job_dump_data *dump, struct component_loc **clp, int *nump) { struct component_loc *cl; int num; int rc; /* Get memory for image, parmline, ramdisk, loader */ cl = misc_calloc(3, sizeof(struct component_loc)); if (cl == NULL) return -1; /* Fill in component data */ num = 0; rc = set_cl_element(&cl[num++], "kernel image", dump->image, &dump->image_addr, 0, 0x10000, MAXIMUM_PHYSICAL_BLOCKSIZE); if (rc) goto error; rc = set_cl_element(&cl[num++], "parmline", NULL, &dump->parm_addr, MAXIMUM_PARMLINE_SIZE, 0, MAXIMUM_PHYSICAL_BLOCKSIZE); if (rc) goto error; if (dump->ramdisk) { rc = set_cl_element(&cl[num++], "initial ramdisk", dump->ramdisk, &dump->ramdisk_addr, 0, 0, 0x10000); if (rc) goto error; } *clp = cl; *nump = num; return 0; error: free(cl); return rc; } static int get_ipl_tape_components(struct job_ipl_tape_data *ipl_tape, struct component_loc **clp, int *nump) { struct component_loc *cl; int num; int rc; /* Get memory for image, parmline, ramdisk */ cl = misc_calloc(3, sizeof(struct component_loc)); if (cl == NULL) return -1; /* Fill in component data */ num = 0; rc = set_cl_element(&cl[num++], "kernel image", ipl_tape->image, &ipl_tape->image_addr, 0, 0x10000, MAXIMUM_PHYSICAL_BLOCKSIZE); if (rc) goto error; /* Enhance the image size value for tape loader specific logic */ cl[0].size = ALIGN(cl[0].size + 0x100, MAXIMUM_PHYSICAL_BLOCKSIZE); if (ipl_tape->parmline) { rc = set_cl_element(&cl[num++], "parmline", NULL, &ipl_tape->parm_addr, MAXIMUM_PARMLINE_SIZE, 0, MAXIMUM_PHYSICAL_BLOCKSIZE); if (rc) goto error; } if (ipl_tape->ramdisk) { rc = set_cl_element(&cl[num++], "initial ramdisk", ipl_tape->ramdisk, &ipl_tape->ramdisk_addr, 0, 0, 0x10000); if (rc) goto error; } *clp = cl; *nump = num; return 0; error: free(cl); return rc; } static int check_component_address_data(struct component_loc *cl, int num, char *name, unsigned long address_limit) { int i; /* Check for address limit */ for (i = 0; i < num; i++) { if (*cl[i].addrp == UNSPECIFIED_ADDRESS) continue; if (*cl[i].addrp + cl[i].size > address_limit) { if (name != NULL) error_text("Section '%s'", name); error_reason("Component '%s' exceeds available address " "space (limit is 0x%08x)", cl[i].name, address_limit); return -1; } if (*cl[i].addrp < MINIMUM_ADDRESS) { if (name != NULL) error_text("Section '%s'", name); error_reason("Component '%s' falls below available " "address space (limit is 0x%08x)", cl[i].name, MINIMUM_ADDRESS); return -1; } } /* Check for overlap */ for (i = 0; i < num - 1; i++) { if (*cl[i].addrp == UNSPECIFIED_ADDRESS || *cl[i + 1].addrp == UNSPECIFIED_ADDRESS) continue; if (*cl[i].addrp + cl[i].size > *cl[i + 1].addrp) { if (name != NULL) error_text("Section '%s'", name); error_reason("Components '%s' and '%s' overlap", cl[i].name, cl[i + 1].name); return -1; } } return 0; } static int finalize_component_address_data(struct component_loc *cl, int num, unsigned long address_limit) { struct component_loc swap; address_t addr; int i; int j; int k; /* Calculate unspecified addresses */ for (i = 0; i < num; i++) { if (*cl[i].addrp != UNSPECIFIED_ADDRESS) continue; for (j = -1; j < i; j++) { if (j < 0) { /* Try address before first component */ addr = MINIMUM_ADDRESS; } else { /* Try address after component j */ addr = *cl[j].addrp + cl[j].size; if (addr < MINIMUM_ADDRESS) addr = MINIMUM_ADDRESS; } addr = ALIGN(addr, cl[i].align); if (addr + cl[i].size > address_limit) { error_text("Could not fit component '%s' into " "available address space", cl[i].name); return -1; } /* Check for enough room */ if (*cl[j + 1].addrp != UNSPECIFIED_ADDRESS && addr + cl[i].size > *cl[j + 1].addrp) continue; *cl[i].addrp = addr; /* If there is no next component we are done */ if (i == j + 1) break; /* Restore sort order */ swap = cl[j + 1]; cl[j + 1] = cl[i]; for (k = i; k > j + 2; k--) cl[k] = cl[k - 1]; cl[j + 2] = swap; break; } } return 0; } static int finalize_ipl_address_data(struct job_ipl_data* ipl, char *name) { unsigned long address_limit; struct component_loc *cl; int num; int rc; address_limit = ipl->is_kdump ? ADDRESS_LIMIT_KDUMP : ADDRESS_LIMIT; rc = get_ipl_components(ipl, &cl, &num); if (rc) return rc; sort_cl_array(cl, num); rc = check_component_address_data(cl, num, name, address_limit); if (rc) goto out_free; rc = finalize_component_address_data(cl, num, address_limit); out_free: free(cl); return rc; } static int finalize_dump_address_data(struct job_dump_data* dump, char *name) { struct component_loc *cl; int num; int rc; rc = get_dump_components(dump, &cl, &num); if (rc) return rc; sort_cl_array(cl, num); rc = check_component_address_data(cl, num, name, ADDRESS_LIMIT); if (rc) goto out_free; rc = finalize_component_address_data(cl, num, ADDRESS_LIMIT); out_free: free(cl); return rc; } static int finalize_ipl_tape_address_data(struct job_ipl_tape_data* ipl_tape, char *name) { struct component_loc *cl; int num; int rc; int i; rc = get_ipl_tape_components(ipl_tape, &cl, &num); if (rc) return rc; sort_cl_array(cl, num); rc = check_component_address_data(cl, num, name, ADDRESS_LIMIT); if (rc) goto out_free; rc = finalize_component_address_data(cl, num, ADDRESS_LIMIT); /* The loader needs a ramdisk_addr anyway */ if (ipl_tape->ramdisk_addr == 0) { for (i = 0; i < num; i++) { if (*cl[i].addrp == ipl_tape->image_addr) ipl_tape->ramdisk_addr = *cl[i].addrp + cl[i].size; } } out_free: free(cl); return rc; } static int check_job_ipl_data(struct job_ipl_data *ipl, char* name) { int rc; if (ipl->image != NULL) { rc = misc_check_readable_file(ipl->image); if (rc) { if (name == NULL) { error_text("Image file '%s'", ipl->image); } else { error_text("Image file '%s' in section '%s'", ipl->image, name); } return rc; } } if (ipl->ramdisk != NULL) { rc = misc_check_readable_file(ipl->ramdisk); if (rc) { if (name == NULL) { error_text("Ramdisk file '%s'", ipl->ramdisk); } else { error_text("Ramdisk file '%s' in section '%s'", ipl->ramdisk, name); } return rc; } } return finalize_ipl_address_data(ipl, name); } static int check_job_segment_data(struct job_segment_data* segment, char* name) { int rc; if (segment->segment != NULL) { rc = misc_check_readable_file(segment->segment); if (rc) { if (name == NULL) { error_text("Segment file '%s'", segment->segment); } else { error_text("Segment file '%s' in section '%s'", segment->segment, name); } return rc; } } return 0; } static int check_job_dump_data(struct job_dump_data* dump, char* name) { int rc; if (dump->device != NULL) { rc = misc_check_writable_device(dump->device, 1, 1); if (rc) { if (name == NULL) { error_text("Dump device '%s'", dump->device); } else { error_text("Dump device '%s' in section '%s'", dump->device, name); } return rc; } } return 0; } int check_job_dump_images(struct job_dump_data* dump, char* name) { int rc; /* Add data needed to convert fs dump job to IPL job */ rc = misc_check_readable_file(FSDUMP_PART_IMAGE); if (rc) { error_text("Need external file '%s' for partition dump", FSDUMP_PART_IMAGE); return rc; } dump->image = misc_strdup(FSDUMP_PART_IMAGE); if (dump->image == NULL) return -1; dump->image_addr = DEFAULT_IMAGE_ADDRESS; /* Ramdisk is no longer required with new initramfs dump system */ if (misc_check_readable_file(FSDUMP_PART_RAMDISK)) dump->ramdisk = NULL; else { dump->ramdisk = misc_strdup(FSDUMP_PART_RAMDISK); if (dump->ramdisk == NULL) return -1; dump->ramdisk_addr = UNSPECIFIED_ADDRESS; } dump->parm_addr = UNSPECIFIED_ADDRESS; return finalize_dump_address_data(dump, name); } static int check_job_menu_data(struct job_menu_data* menu) { int rc; int i; for (i=0; i<menu->num; i++) { switch (menu->entry[i].id) { case job_ipl: rc = check_job_ipl_data(&menu->entry[i].data.ipl, menu->entry[i].name); if (rc) return rc; break; case job_print_usage: case job_print_version: case job_segment: case job_dump_partition: case job_mvdump: case job_menu: case job_ipl_tape: break; } } return 0; } static int check_job_ipl_tape_data(struct job_ipl_tape_data *ipl, char* name) { int rc; if (ipl->device != NULL) { rc = misc_check_writable_device(ipl->device, 1, 1); if (rc) { if (name == NULL) { error_text("Tape device '%s'", ipl->device); } else { error_text("Tape device '%s' in section '%s'", ipl->device, name); } return rc; } } if (ipl->image != NULL) { rc = misc_check_readable_file(ipl->image); if (rc) { if (name == NULL) { error_text("Image file '%s'", ipl->image); } else { error_text("Image file '%s' in section '%s'", ipl->image, name); } return rc; } } if (ipl->ramdisk != NULL) { rc = misc_check_readable_file(ipl->ramdisk); if (rc) { if (name == NULL) { error_text("Ramdisk file '%s'", ipl->ramdisk); } else { error_text("Ramdisk file '%s' in section '%s'", ipl->ramdisk, name); } return rc; } } return finalize_ipl_tape_address_data(ipl, name); } static int check_job_mvdump_data(struct job_mvdump_data* dump, char* name) { int rc; size_t size, i, j, k; char* buffer; rc = misc_read_file(dump->device_list, &buffer, &size, 0); if (rc) { if (name == NULL) { error_text("Dump target list '%s'", dump->device_list); } else { error_text("Dump target list '%s' in section '%s'", dump->device_list, name); } return rc; } if (size == 0) { error_text("Dump target list '%s' is empty.", dump->device_list); free(buffer); return -1; } for (i = 0, j = 0, k = 0 ; i < size; i++) { if (buffer[i] != '\n') buffer[j++] = buffer[i]; else if (j > 0) { if (k == MAX_DUMP_VOLUMES) { error_text("Dump target list '%s' contains " "more than %d entries.", dump->device_list, k); free(buffer); return -1; } buffer[j] = 0; dump->device[k] = misc_strdup(buffer); if (dump->device[k] == NULL) return -1; k++; j = 0; } } free(buffer); dump->device_count = k; for (i = 0; i < (size_t) dump->device_count; i++) { rc = misc_check_writable_device(dump->device[i], 1, 0); if (rc) { error_text("Dump target '%s'", dump->device[i]); return rc; } for (j = 0; j < i; j++) { if (!strcmp(dump->device[i], dump->device[j])) { error_text("Dump target list '%s' contains " "duplicate entry '%s'.", dump->device_list, dump->device[i]); return -1; } } } return 0; } static int check_job_data(struct job_data* job) { int rc = -1; /* Check for missing information */ if (job->target.bootmap_dir != NULL) { rc = misc_check_writable_directory(job->target.bootmap_dir); if (rc) { if (job->name == NULL) { error_text("Target directory '%s'", job->target.bootmap_dir); } else { error_text("Target directory '%s' in section " "'%s'", job->target.bootmap_dir, job->name); } return rc; } } switch (job->id) { case job_print_usage: case job_print_version: rc = 0; break; case job_ipl: rc = check_job_ipl_data(&job->data.ipl, job->name); break; case job_menu: rc = check_job_menu_data(&job->data.menu); break; case job_segment: rc = check_job_segment_data(&job->data.segment, job->name); break; case job_dump_partition: rc = check_job_dump_data(&job->data.dump, job->name); break; case job_ipl_tape: rc = check_job_ipl_tape_data(&job->data.ipl_tape, job->name); break; case job_mvdump: rc = check_job_mvdump_data(&job->data.mvdump, job->name); } return rc; } static int extract_address (char* string, address_t* address) { unsigned long long result; /* Find trailing comma */ string = strrchr(string, ','); if (string != NULL) { /* Try to scan a hexadecimal address */ if (sscanf(string + 1, "%llx", &result) == 1) { /* Got a match, remove address from string */ *string = '\0'; *address = (address_t) result; return 0; } } return -1; } static int extract_memsize(char* string, uint64_t* size) { unsigned long long result; /* Find trailing comma */ string = strrchr(string, ','); if (string == NULL) return -1; if (sscanf(string + 1, "%lld", &result) != 1) return -1; switch(string[strlen(string) - 1]) { case 'G': case 'g': /* Number in gigabytes */ result *= 1024LL * 1024LL * 1024LL; break; case 'M': case 'm': /* Number in megabytes*/ result *= 1024LL * 1024LL; break; case 'K': case 'k': /* Number in kilobytes */ result *= 1024LL; break; default: /* Number in bytes */ break; } *string = '\0'; *size = result; return 0; } static char* append_parmline(char* a, char* b) { char* buffer; int insert_blank; /* Insert blank if none is present at end of A */ if (strlen(a) == 0) insert_blank = 0; else insert_blank = (a[strlen(a) - 1] != ' '); buffer = misc_malloc(strlen(a) + strlen(b) + (insert_blank ? 2 : 1)); if (buffer != NULL) { if (insert_blank) sprintf(buffer, "%s %s", a, b); else sprintf(buffer, "%s%s", a, b); } return buffer; } /* Combine given parmfile FILENAME and parmline LINE into resulting PARMLINE * by appending lines as necessary. Parmline load address will be stored in * ADDRESS. */ static int get_parmline(char* filename, char* line, char** parmline, address_t* address, char* section) { char* buffer; char* result; address_t addr; size_t len; int rc; int from; int to; int got_lf; addr = UNSPECIFIED_ADDRESS; if (filename != NULL) { /* Need a filename copy to be able to change it */ filename = misc_strdup(filename); if (filename == NULL) return -1; extract_address(filename, &addr); rc = misc_read_file(filename, &buffer, &len, 1); if (rc) { if (section == NULL) error_text("Parmfile '%s'", filename); else { error_text("Parmfile '%s' in section '%s'", filename, section); } free(filename); return rc; } free(filename); /* Remove \n's from parmfile */ got_lf = 0; for (from=0, to=0; buffer[from] != 0; from++) if (buffer[from] != '\n') { buffer[to++] = buffer[from]; got_lf = 0; } else { if (!got_lf) buffer[to++] = ' '; got_lf = 1; } buffer[to] = 0; /* Combine parmfile and parmline if present */ if (line == NULL) result = buffer; else { /* Append parmline to end of parmfile content */ result = append_parmline(buffer, line); free(buffer); if (result == NULL) return -1; } } else if (line != NULL) { result = misc_strdup(line); if (result == NULL) return -1; } else result = NULL; /* Check for maximum length */ if (result) { len = strlen(result); if (len > MAXIMUM_PARMLINE_SIZE) { error_text("The length of the parameters line " "(%d bytes) exceeds the allowed maximum " "(%d bytes)", len, MAXIMUM_PARMLINE_SIZE); free(result); return -1; } } *parmline = result; *address = addr; return 0; } #define MEGABYTE_MASK (1024LL * 1024LL - 1LL) int type_from_target(char *target, disk_type_t *type) { switch (scan_get_target_type(target)) { case target_type_scsi: *type = disk_type_scsi; return 0; case target_type_fba: *type = disk_type_fba; return 0; case target_type_ldl: *type = disk_type_eckd_ldl; return 0; case target_type_cdl: *type = disk_type_eckd_cdl; return 0; default: return -1; } } static int get_job_from_section_data(char* data[], struct job_data* job, char* section) { int rc; switch (scan_get_section_type(data)) { case section_ipl: /* IPL job */ job->id = job_ipl; /* Fill in name of bootmap directory */ job->target.bootmap_dir = misc_strdup(data[(int) scan_keyword_target]); if (job->target.bootmap_dir == NULL) return -1; /* Fill in target */ if (data[(int) scan_keyword_targetbase] != NULL) { job->target.targetbase = misc_strdup(data[(int) scan_keyword_targetbase]); if (job->target.targetbase == NULL) return -1; } if (data[(int) scan_keyword_targettype] != NULL) { if (type_from_target( data[(int) scan_keyword_targettype], &job->target.targettype)) return -1; } if (data[(int) scan_keyword_targetgeometry] != NULL) { job->target.targetcylinders = atoi(strtok(data[(int) scan_keyword_targetgeometry], ",")); job->target.targetheads = atoi(strtok(NULL, ",")); job->target.targetsectors = atoi(strtok(NULL, ",")); } if (data[(int) scan_keyword_targetblocksize] != NULL) job->target.targetblocksize = atoi(data[(int) scan_keyword_targetblocksize]); if (data[(int) scan_keyword_targetoffset] != NULL) job->target.targetoffset = atol(data[(int) scan_keyword_targetoffset]); /* Fill in name and address of image file */ job->data.ipl.image = misc_strdup( data[(int) scan_keyword_image]); if (job->data.ipl.image == NULL) return -1; if (extract_address(job->data.ipl.image, &job->data.ipl.image_addr)) { job->data.ipl.image_addr = DEFAULT_IMAGE_ADDRESS; } /* Fill in parmline */ rc = get_parmline(data[(int) scan_keyword_parmfile], data[(int) scan_keyword_parameters], &job->data.ipl.parmline, &job->data.ipl.parm_addr, section); if (rc) return rc; /* Fill in name and address of ramdisk file */ if (data[(int) scan_keyword_ramdisk] != NULL) { job->data.ipl.ramdisk = misc_strdup(data[(int) scan_keyword_ramdisk]); if (job->data.ipl.ramdisk == NULL) return -1; if (extract_address(job->data.ipl.ramdisk, &job->data.ipl.ramdisk_addr)) { job->data.ipl.ramdisk_addr = UNSPECIFIED_ADDRESS; } } /* Fill in kdump */ if (data[(int) scan_keyword_kdump] != NULL) { if (strcmp(data[(int) scan_keyword_kdump], "auto") == 0) { job->data.ipl.is_kdump = 1; } else { error_reason("Invalid kdump setting '%s'", data[(int) scan_keyword_kdump]); return -1; } } break; case section_ipl_tape: /* Tape IPL job */ job->id = job_ipl_tape; /* Fill in name of tape device */ job->data.ipl_tape.device = misc_strdup(data[(int) scan_keyword_tape]); if (job->data.ipl_tape.device == NULL) return -1; /* Fill in name and address of image file */ job->data.ipl_tape.image = misc_strdup( data[(int) scan_keyword_image]); if (job->data.ipl_tape.image == NULL) return -1; if (extract_address(job->data.ipl_tape.image, &job->data.ipl_tape.image_addr)) { job->data.ipl_tape.image_addr = DEFAULT_IMAGE_ADDRESS; } /* Fill in parmline */ rc = get_parmline(data[(int) scan_keyword_parmfile], data[(int) scan_keyword_parameters], &job->data.ipl_tape.parmline, &job->data.ipl_tape.parm_addr, section); if (rc) return rc; /* Fill in name and address of ramdisk file */ if (data[(int) scan_keyword_ramdisk] != NULL) { job->data.ipl_tape.ramdisk = misc_strdup(data[(int) scan_keyword_ramdisk]); if (job->data.ipl_tape.ramdisk == NULL) return -1; if (extract_address(job->data.ipl_tape.ramdisk, &job->data.ipl_tape.ramdisk_addr)) { job->data.ipl_tape.ramdisk_addr = UNSPECIFIED_ADDRESS; } } break; case section_segment: /* SEGMENT LOAD job */ job->id = job_segment; /* Fill in name of bootmap directory */ job->target.bootmap_dir = misc_strdup(data[(int) scan_keyword_target]); if (job->target.bootmap_dir == NULL) return -1; /* Fill in segment filename */ job->data.segment.segment = misc_strdup(data[(int) scan_keyword_segment]); if (job->data.segment.segment == NULL) return -1; extract_address(job->data.segment.segment, &job->data.segment.segment_addr); break; case section_dump: /* DUMP TO PARTITION job */ job->id = job_dump_partition; /* Fill in device node filename */ job->data.dump.device = misc_strdup( data[(int) scan_keyword_dumpto]); if (job->data.dump.device == NULL) return -1; /* Check for mem size specification */ if (extract_memsize(job->data.dump.device, &job->data.dump.mem) == 0) { /* Ensure megabyte alignment of size */ job->data.dump.mem = (job->data.dump.mem + MEGABYTE_MASK) & ~MEGABYTE_MASK; printf("Found specification of dump size limit " "to %lldMB\n", (unsigned long long) job->data.dump.mem / (1024LL * 1024LL)); } else job->data.dump.mem = -1LL; break; case section_mvdump: /* DUMP TO MULTI-VOLUME job */ job->id = job_mvdump; /* Fill in name of file containing the multiple partitions */ job->data.mvdump.device_list = misc_strdup( data[(int) scan_keyword_mvdump]); if (job->data.mvdump.device_list == NULL) return -1; /* Check for mem size specification */ if (extract_memsize(job->data.mvdump.device_list, &job->data.mvdump.mem) == 0) { /* Ensure megabyte alignment of size */ job->data.mvdump.mem = (job->data.mvdump.mem + MEGABYTE_MASK) & ~MEGABYTE_MASK; printf("Found specification of dump size limit " "to %lldMB\n", (unsigned long long) job->data.mvdump.mem / (1024LL * 1024LL)); } else job->data.mvdump.mem = -1LL; break; default: /* Should not happen */ job->id = job_print_usage; break; } return 0; } static int get_menu_job(struct scan_token* scan, char* menu, struct job_data* job) { char* data[SCAN_KEYWORD_NUM]; struct job_data* temp_job; char* section; int index; int i; int j; int current; int rc; job->id = job_menu; job->name = misc_strdup(menu); if (job->name == NULL) return -1; /* Extract menu job from configuration data in SCAN */ index = scan_find_section(scan, menu, scan_id_menu_heading, 0); if (index<0) { error_reason("Menu section '%s' not found", menu); return -1; } /* Count menu entries, find default entry and target directory */ job->data.menu.num = 0; job->data.menu.default_pos = -1; job->data.menu.prompt = MENU_DEFAULT_PROMPT; job->data.menu.timeout = MENU_DEFAULT_TIMEOUT; for (i=index+1; (scan[i].id != scan_id_empty) && (scan[i].id != scan_id_section_heading) && (scan[i].id != scan_id_menu_heading); i++) { if (scan[i].id == scan_id_number_assignment) { if (job->data.menu.default_pos < 0) job->data.menu.default_pos = scan[i].content.number.number; job->data.menu.num++; } else if (scan[i].id == scan_id_keyword_assignment) { switch (scan[i].content.keyword.keyword) { case scan_keyword_default: job->data.menu.default_pos = atol(scan[i].content.keyword.value); break; case scan_keyword_prompt: job->data.menu.prompt = atol(scan[i].content.keyword.value); break; case scan_keyword_timeout: job->data.menu.timeout = atol(scan[i].content.keyword.value); break; case scan_keyword_target: job->target.bootmap_dir = misc_strdup( scan[i].content.keyword.value); if (job->target.bootmap_dir == NULL) return -1; break; case scan_keyword_targetbase: job->target.targetbase = misc_strdup( scan[i].content.keyword.value); if (job->target.targetbase == NULL) return -1; break; case scan_keyword_targettype: if (type_from_target( scan[i].content.keyword.value, &job->target.targettype)) return -1; break; case scan_keyword_targetgeometry: job->target.targetcylinders = atoi(strtok( scan[i].content.keyword.value, ",")); job->target.targetheads = atoi(strtok(NULL, ",")); job->target.targetsectors = atoi(strtok(NULL, ",")); break; case scan_keyword_targetblocksize: job->target.targetblocksize = atoi( scan[i].content.keyword.value); break; case scan_keyword_targetoffset: job->target.targetoffset = atol( scan[i].content.keyword.value); break; default: /* Should not happen */ break; } } } if (job->data.menu.num == 0) { /* Should not happen */ error_reason("No entries found in menu '%s'", menu); return -1; } /* Allocate array */ job->data.menu.entry = misc_malloc(sizeof(struct job_menu_entry) * job->data.menu.num); if (job->data.menu.entry == NULL) return -1; memset((void *) job->data.menu.entry, 0, sizeof(struct job_menu_entry) * job->data.menu.num); /* Fill in data */ current = 0; for (i=index+1; (scan[i].id != scan_id_empty) && (scan[i].id != scan_id_section_heading) && (scan[i].id != scan_id_menu_heading); i++) { if (scan[i].id != scan_id_number_assignment) continue; job->data.menu.entry[current].pos = scan[i].content.number.number; job->data.menu.entry[current].name = misc_strdup(scan[i].content.number.value); if (job->data.menu.entry[current].name == NULL) return -1; section = job->data.menu.entry[current].name; /* Search for section in config file */ j = scan_find_section(scan, section, scan_id_section_heading, 0); if (j<0) { error_reason("Configuration section '%s' not found", section); return -1; } /* Get section_data from scan */ memset(&data, 0, sizeof(data)); for (j++; scan[j].id == scan_id_keyword_assignment; j++) data[(int) scan[j].content.keyword.keyword] = scan[j].content.keyword.value; /* Get job from section_data */ temp_job = (struct job_data *) misc_malloc( sizeof(struct job_data)); if (temp_job == NULL) return -1; memset((void *) temp_job, 0, sizeof(struct job_data)); rc = get_job_from_section_data(data, temp_job, job->data.menu.entry[current].name); if (rc) { job_free(temp_job); return rc; } /* Copy data from temporary job */ switch (temp_job->id) { case job_ipl: job->data.menu.entry[current].id = job_ipl; job->data.menu.entry[current].data.ipl = temp_job->data.ipl; memset((void *) &temp_job->data.ipl, 0, sizeof(struct job_ipl_data)); break; default: error_reason("Section '%s' cannot be included " "in menu '%s'", section, menu); rc = -1; break; } job_free(temp_job); if (rc) return rc; current++; } return 0; } static int get_default_section(struct scan_token* scan, char** section, int* is_menu) { int i; /* Find defaultboot section */ i = scan_find_section(scan, DEFAULTBOOT_SECTION, scan_id_section_heading, 0); if (i<0) { error_reason("No '" DEFAULTBOOT_SECTION "' section found and " "no section specified on command line"); return -1; } /* Find 'default' or 'defaultmenu' keyword */ for (i++; scan[i].id == scan_id_keyword_assignment; i++) { if (scan[i].content.keyword.keyword == scan_keyword_default) { *section = scan[i].content.keyword.value; *is_menu = 0; return 0; } if (scan[i].content.keyword.keyword == scan_keyword_defaultmenu) { *section = scan[i].content.keyword.value; *is_menu = 1; return 0; } } /* Should not happen */ error_reason("No default section specified"); return -1; } /* Extract job data from configuration data in SCAN. SECTION specifies the * name of the section to use or NULL if the default section should be used. * Upon success, return zero, store job data in JOB and set NAME to point to * the section name. Return non-zero otherwise. */ static int get_section_job(struct scan_token* scan, char* section, struct job_data* job, char* extra_parmline) { char* data[SCAN_KEYWORD_NUM]; char* buffer; int rc; int i; if (section == NULL) { rc = get_default_section(scan, &section, &i); if (rc) return rc; if (i) { /* 'defaultmenu' was specified */ rc = get_menu_job(scan, section, job); return rc; } } if (strcmp(section, DEFAULTBOOT_SECTION) == 0) { error_reason("Special section '" DEFAULTBOOT_SECTION "' cannot " "be used as target section"); return -1; } /* Search for section in config file */ i = scan_find_section(scan, section, scan_id_section_heading, 0); if (i<0) { error_reason("Configuration section '%s' not found", section); return -1; } job->name = misc_strdup(section); if (job->name == NULL) return -1; /* Get section_data from scan */ memset(&data, 0, sizeof(data)); for (i++; scan[i].id == scan_id_keyword_assignment; i++) data[(int) scan[i].content.keyword.keyword] = scan[i].content.keyword.value; /* Get job from section_data */ rc = get_job_from_section_data(data, job, job->name); if (rc) return rc; /* Append extra parmline */ if (extra_parmline != NULL) { switch (job->id) { case job_ipl: if (job->data.ipl.parmline == NULL) buffer = misc_strdup(extra_parmline); else { buffer = append_parmline( job->data.ipl.parmline, extra_parmline); free(job->data.ipl.parmline); } job->data.ipl.parmline = buffer; if (buffer == NULL) return -1; break; case job_segment: error_reason("Option 'parameters' cannot be used with " "section '%s'", section); return -1; break; case job_dump_partition: error_reason("Option 'parameters' cannot be used with " "partition dump section '%s'", section); return -1; break; default: /* Should not happen */ break; } } return 0; } static int get_job_from_config_file(struct command_line* cmdline, struct job_data* job) { struct scan_token* scan; struct scan_token* new_scan; char* filename; char* source; int rc; /* Read configuration file */ if (cmdline->config != NULL) { /* Use config file as provided on command line */ filename = cmdline->config; source = " (from command line)"; } else if (getenv(ZIPL_CONF_VAR) != NULL) { /* Use config file specified by environment variable */ filename = getenv(ZIPL_CONF_VAR); source = " (from environment variable " ZIPL_CONF_VAR ")"; } else { /* Use default config file */ filename = ZIPL_DEFAULT_CONF; source = ""; } printf("Using config file '%s'%s\n", filename, source); rc = scan_file(filename, &scan); if (rc) { error_text("Config file '%s'", filename); return rc; } if ((cmdline->menu == NULL) && (cmdline->section == NULL)) { rc = scan_check_defaultboot(scan); if (rc < 0) { error_text("Config file '%s'", filename); scan_free(scan); return rc; } if (rc == 1) { new_scan = scan_build_automenu(scan); scan_free(scan); if (new_scan == NULL) { error_text("Config file '%s'", filename); return -1; } scan = new_scan; } } rc = scan_check(scan); if (rc) { error_text("Config file '%s'", filename); scan_free(scan); return rc; } /* Get job from config file data */ if (cmdline->menu != NULL) rc = get_menu_job(scan, cmdline->menu, job); else { rc = get_section_job(scan, cmdline->section, job, cmdline->data[(int) scan_keyword_parameters]); } /* Make sure no '--parameters' option was specified when writing a * menu section. */ if (job->id == job_menu && cmdline->data[(int) scan_keyword_parameters]) { error_text("Option 'parameters' cannot be used with a menu " "section"); rc = -1; } scan_free(scan); return rc; } int job_get(int argc, char* argv[], struct job_data** data) { struct command_line cmdline; struct job_data* job; int rc; rc = get_command_line(argc, argv, &cmdline); if (rc) return rc; job = (struct job_data *) misc_malloc(sizeof(struct job_data)); if (job == NULL) return -1; memset((void *) job, 0, sizeof(struct job_data)); /* Fill in global options */ job->noninteractive = cmdline.noninteractive; job->verbose = cmdline.verbose; job->add_files = cmdline.add_files; job->data.mvdump.force = cmdline.force; job->dry_run = cmdline.dry_run; /* Get job data from user input */ if (cmdline.help) { job->command_line = 1; job->id = job_print_usage; } else if (cmdline.version) { job->command_line = 1; job->id = job_print_version; } else if (cmdline.type != section_invalid) { job->command_line = 1; rc = get_job_from_section_data(cmdline.data, job, NULL); } else { job->command_line = 0; rc = get_job_from_config_file(&cmdline, job); } if (rc) { job_free(job); return rc; } /* Check job data for validity */ rc = check_job_data(job); if (rc) { job_free(job); return rc; } *data = job; return rc; }
hreinecke/s390-tools
zipl/src/job.c
C
gpl-2.0
44,616
#! /bin/sh # Copyright (C) 1997-2018 Free Software Foundation, Inc. # # 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, see <https://www.gnu.org/licenses/>. # Test _DEPENDENCIES variable. From Lee Iverson. . test-init.sh cat >> configure.ac << 'END' AC_PROG_CC AC_SUBST(DEPS) END cat > Makefile.am << 'END' bin_PROGRAMS = TerraVision TerraVision_SOURCES = \ AboutDialog.c Clock.c Dialogs.c DrawModel.c \ TsmWidget.c Gats.c GATSDialogs.c Model.c ModelAnim.c \ ScannedMap.c \ TerraVision.c TerraVisionAvs.c TerraVisionCAVE.c \ Texture.c ThreeDControl.c ThreeDPanel.c \ ThreeDWidget.c ThreeDWidget1.c TileManager.c \ TileRequester.c TwoDWidget.c \ Visible.c RequestGenerator.c X11FrameGrab.c \ matrix.c pixmaps.c xpmhash.c xpmread.c xcolor.c xv24to8.c DEPS = @DEPS@ TerraVision_DEPENDENCIES = $(DEPS) END $ACLOCAL $AUTOMAKE
komh/automake-os2
t/depend3.sh
Shell
gpl-2.0
1,386
package br.com.br.gatend.GestaoCliente.v1.model.vo; import oracle.jbo.server.ViewObjectImpl; // --------------------------------------------------------------------- // --- File generated by Oracle ADF Business Components Design Time. // --- Wed Jul 16 14:20:16 BRT 2014 // --- Custom code may be added to this class. // --- Warning: Do not modify method signatures of generated methods. // --------------------------------------------------------------------- public class FndDocumentsVOImpl extends ViewObjectImpl { /** * This is the default constructor (do not remove). */ public FndDocumentsVOImpl() { } }
mmacedoeu/adf_gcli
Model/src/br/com/br/gatend/GestaoCliente/v1/model/vo/FndDocumentsVOImpl.java
Java
gpl-2.0
663
/* * RapidMiner * * Copyright (C) 2001-2008 by Rapid-I and the contributors * * Complete list of developers available at our web site: * * http://rapid-i.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.example.set; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import com.rapidminer.example.Attribute; import com.rapidminer.example.AttributeRole; import com.rapidminer.example.AttributeTransformation; import com.rapidminer.example.Attributes; import com.rapidminer.example.Example; import com.rapidminer.example.ExampleSet; import com.rapidminer.example.Statistics; import com.rapidminer.example.table.ExampleTable; /** * An implementation of ExampleSet that allows the replacement of missing values * on the fly. Missing values will be replaced by the average of all other values * or by the mean. * * @author Ingo Mierswa * @version $Id: ReplaceMissingExampleSet.java,v 1.8 2008/05/09 19:22:49 ingomierswa Exp $ */ public class ReplaceMissingExampleSet extends AbstractExampleSet { private static final long serialVersionUID = -5662936146589379273L; /** Currently used attribute weights. Used also for example creation. */ private Map<String, Double> replacementMap; /** The parent example set. */ private ExampleSet parent; public ReplaceMissingExampleSet(ExampleSet exampleSet) { this(exampleSet, null); } public ReplaceMissingExampleSet(ExampleSet exampleSet, Map<String, Double> replacementMap) { this.parent = (ExampleSet)exampleSet.clone(); if (replacementMap == null) { this.replacementMap = new HashMap<String, Double>(); for (Attribute attribute : parent.getAttributes()) addReplacement(attribute); } else { this.replacementMap = replacementMap; } Iterator<AttributeRole> a = this.parent.getAttributes().allAttributeRoles(); while (a.hasNext()) { AttributeRole role = a.next(); Attribute currentAttribute = role.getAttribute(); currentAttribute.addTransformation(new AttributeTransformationReplaceMissing(this.replacementMap)); } } /** Clone constructor. */ public ReplaceMissingExampleSet(ReplaceMissingExampleSet exampleSet) { this.parent = (ExampleSet)exampleSet.parent.clone(); this.replacementMap = new HashMap<String, Double>(); for (String name : exampleSet.replacementMap.keySet()) { this.replacementMap.put(name, Double.valueOf(exampleSet.replacementMap.get(name).doubleValue())); } Iterator<AttributeRole> a = this.parent.getAttributes().allAttributeRoles(); while (a.hasNext()) { AttributeRole role = a.next(); Attribute currentAttribute = role.getAttribute(); AttributeTransformation transformation = currentAttribute.getLastTransformation(); if (transformation != null) if (transformation instanceof AttributeTransformationReplaceMissing) ((AttributeTransformationReplaceMissing)transformation).setReplacementMap(this.replacementMap); } } public Map<String, Double> getReplacementMap() { return this.replacementMap; } public void addReplacement(Attribute attribute) { recalculateAttributeStatistics(attribute); if (attribute.isNominal()) this.replacementMap.put(attribute.getName(), getStatistics(attribute, Statistics.MODE)); else this.replacementMap.put(attribute.getName(), getStatistics(attribute, Statistics.AVERAGE)); } public Attributes getAttributes() { return this.parent.getAttributes(); } public boolean equals(Object o) { if (!super.equals(o)) return false; if (!(o instanceof ReplaceMissingExampleSet)) return false; boolean result = super.equals(o); if (result) { Map<String,Double> otherMap = ((ReplaceMissingExampleSet)o).replacementMap; if (this.replacementMap.size() != otherMap.size()) return false; for (String name : this.replacementMap.keySet()) { if (!this.replacementMap.get(name).equals(otherMap.get(name))) return false; } } return true; } public int hashCode() { return super.hashCode() ^ replacementMap.hashCode(); } /** * Creates a new example set reader. */ public Iterator<Example> iterator() { return new AttributesExampleReader(parent.iterator(), this); } public Example getExample(int index) { return this.parent.getExample(index); } public ExampleTable getExampleTable() { return parent.getExampleTable(); } public int size() { return parent.size(); } }
ntj/ComplexRapidMiner
src/com/rapidminer/example/set/ReplaceMissingExampleSet.java
Java
gpl-2.0
5,304
package com.lionsteel.tiles.Scenes.GameScenes; import org.andengine.entity.modifier.LoopEntityModifier; import org.andengine.entity.modifier.RotationModifier; import org.andengine.entity.modifier.ScaleModifier; import org.andengine.entity.modifier.SequenceEntityModifier; import org.andengine.entity.primitive.Rectangle; import org.andengine.entity.text.Text; import org.andengine.util.debug.Debug; import org.andengine.util.modifier.ease.EaseCubicIn; import org.andengine.util.modifier.ease.EaseCubicOut; import com.lionsteel.tiles.SharedResources; import com.lionsteel.tiles.SongManager; import com.lionsteel.tiles.BaseClasses.PracticeGameScene; import com.lionsteel.tiles.BaseClasses.TilesMenuButton; import com.lionsteel.tiles.BaseClasses.TilesMenuScene; import com.lionsteel.tiles.BaseClasses.TouchControl; import com.lionsteel.tiles.Constants.Difficulty; import com.lionsteel.tiles.Constants.GameMode; import com.lionsteel.tiles.Constants.TilesConstants; import com.lionsteel.tiles.Scenes.MenuScenes.SetupScene; public class PracticeGameOverScene extends TilesMenuScene implements TilesConstants { final Text titleText; final Text holdToRestartText; final Text gameModeLabel; final Text difficultyLabel; final Text difficultyValue; final Text labelOne; final Text labelTwo; final Text valueOne; final Text valueTwo; final Text newRecordText; final TouchControl restartTouchControl; final float START_Y = 80; public PracticeGameOverScene() { super(); this.setBackgroundEnabled(false); final Rectangle background = new Rectangle(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, activity.getVertexBufferObjectManager()); background.setColor(0, 0, 0, OVERLAY_BACKGROUND_ALPHA); this.attachChild(background); background.setZIndex(BACKGROUND_Z); gameModeLabel = new Text(0, 0, SharedResources.getInstance().headingFont, "Time-Attack", 20, activity.getVertexBufferObjectManager()); gameModeLabel.setScale(.9f); gameModeLabel.setPosition((CAMERA_WIDTH - gameModeLabel.getWidth()) / 2, START_Y); titleText = new Text(0, 0, SharedResources.getInstance().headingFont, "Results", activity.getVertexBufferObjectManager()); titleText.setPosition((CAMERA_WIDTH - titleText.getWidth()) / 2, gameModeLabel.getY() + gameModeLabel.getHeight() + LABEL_SPACING); this.attachChild(titleText); holdToRestartText = new Text(0, 0, SharedResources.getInstance().mFont, "Hold to restart", activity.getVertexBufferObjectManager()); holdToRestartText.setPosition((CAMERA_WIDTH - holdToRestartText.getWidth()) / 2, CAMERA_HEIGHT - holdToRestartText.getHeight() - 50); this.attachChild(holdToRestartText); difficultyLabel = new Text(0, 0, SharedResources.getInstance().mFont, "Difficulty", 20, activity.getVertexBufferObjectManager()); difficultyValue = new Text(0, 0, SharedResources.getInstance().mFont, "Normal", activity.getVertexBufferObjectManager()); labelOne = new Text(0, 0, SharedResources.getInstance().mFont, "Label One", 20, activity.getVertexBufferObjectManager()); labelTwo = new Text(0, 0, SharedResources.getInstance().mFont, "Label Two", 20, activity.getVertexBufferObjectManager()); valueOne = new Text(0, 0, SharedResources.getInstance().mFont, "0", 20, activity.getVertexBufferObjectManager()); valueTwo = new Text(0, 0, SharedResources.getInstance().mFont, "0", 20, activity.getVertexBufferObjectManager()); newRecordText = new Text(0, 0, SharedResources.getInstance().mFont, "New Record!", activity.getVertexBufferObjectManager()); valueOne.setColor(VALUE_TEXT_COLOR); valueTwo.setColor(VALUE_TEXT_COLOR); difficultyValue.setColor(VALUE_TEXT_COLOR); updateTextPositions(); this.attachChild(gameModeLabel); this.attachChild(difficultyLabel); this.attachChild(difficultyValue); this.attachChild(labelOne); this.attachChild(labelTwo); this.attachChild(valueOne); this.attachChild(valueTwo); this.attachChild(newRecordText); //Set this above because this text can bounce if it's a new record valueTwo.setZIndex(FOREGROUND_Z); restartTouchControl = new TouchControl("Ready", new Runnable() { @Override public void run() { if (mParentScene instanceof PracticeGameScene) ((PracticeGameScene) mParentScene).restartGame(); else Debug.e(mParentScene + " not PracticeGameScene"); } }, null); restartTouchControl.setPosition((CAMERA_WIDTH - restartTouchControl.outerImage.getWidth()) / 2, CAMERA_HEIGHT - restartTouchControl.outerImage.getHeight() - 100); this.attachChild(restartTouchControl); final TilesMenuButton quitButton = new TilesMenuButton(SharedResources.getInstance().exitGameButtonRegion, new Runnable() { @Override public void run() { activity.onBackPressed(); } }); quitButton.setPosition(CAMERA_WIDTH - 3 - quitButton.getWidth(), (CAMERA_HEIGHT - quitButton.getHeight()) / 2); addButton(quitButton); this.sortChildren(); } public void setLabels(final String labelOne, final String labelTwo) { this.labelOne.setText(labelOne); this.labelTwo.setText(labelTwo); updateTextPositions(); } public void setValues(final CharSequence valueOne, final CharSequence valueTwo) { this.gameModeLabel.setText(GameMode.getName(SetupScene.getGameMode())); this.difficultyValue.setText(Difficulty.getName(SetupScene.getDifficulty())); this.valueOne.setText(valueOne); this.valueTwo.setText(valueTwo); this.valueTwo.clearEntityModifiers(); this.valueTwo.setScale(1.0f); this.valueTwo.setRotation(0); newRecordText.clearEntityModifiers(); newRecordText.setVisible(false); updateTextPositions(); } private void updateTextPositions() { this.gameModeLabel.setX((CAMERA_WIDTH - gameModeLabel.getWidth()) / 2); this.difficultyLabel.setPosition((CAMERA_WIDTH - difficultyLabel.getWidth()) / 2, titleText.getY() + titleText.getHeight() + LABEL_SPACING * 4); this.difficultyValue.setPosition((CAMERA_WIDTH - difficultyValue.getWidth()) / 2, difficultyLabel.getY() + difficultyLabel.getHeight() + LABEL_SPACING); this.labelOne.setPosition((CAMERA_WIDTH - this.labelOne.getWidth()) / 2, difficultyValue.getY() + difficultyValue.getHeight() + LABEL_SPACING * 2); this.valueOne.setPosition(labelOne.getX() + (labelOne.getWidth() - valueOne.getWidth()) / 2, labelOne.getY() + labelOne.getHeight() + LABEL_SPACING); this.labelTwo.setPosition((CAMERA_WIDTH - this.labelTwo.getWidth()) / 2, valueOne.getY() + valueOne.getHeight() + LABEL_SPACING * 2); this.valueTwo.setPosition(labelTwo.getX() + (labelTwo.getWidth() - valueTwo.getWidth()) / 2, labelTwo.getY() + labelTwo.getHeight() + LABEL_SPACING); this.newRecordText.setPosition((CAMERA_WIDTH-newRecordText.getWidth())/2, valueTwo.getY()+valueTwo.getHeight()+LABEL_SPACING*2); } @Override public void logFlurryEvent() { } @Override public void registerTouchAreas() { registerTouchArea(restartTouchControl.outerImage); super.registerTouchAreas(); } @Override public void initScene() { restartTouchControl.initButton(); SongManager.getInstance().setVolumeMultiplier(MUFFLED_VOLUME); } public void pulseNewRecord() { final float pulseSeconds = 1.0f; final float PULSE_SCALE = 1.6f; final float PULSE_ROTATION = 3; this.valueTwo.registerEntityModifier(new LoopEntityModifier(new SequenceEntityModifier(new ScaleModifier(pulseSeconds / 2, 1.0f, PULSE_SCALE, EaseCubicOut.getInstance()), new ScaleModifier(pulseSeconds / 2, PULSE_SCALE, 1.0f, EaseCubicIn.getInstance())))); this.valueTwo.registerEntityModifier(new LoopEntityModifier(new SequenceEntityModifier(new RotationModifier(pulseSeconds, -PULSE_ROTATION, PULSE_ROTATION), new RotationModifier(pulseSeconds, PULSE_ROTATION, -PULSE_ROTATION)))); this.newRecordText.setVisible(true); this.newRecordText.registerEntityModifier(new LoopEntityModifier(new SequenceEntityModifier(new ScaleModifier(pulseSeconds / 2, 1.0f, PULSE_SCALE, EaseCubicOut.getInstance()), new ScaleModifier(pulseSeconds / 2, PULSE_SCALE, 1.0f, EaseCubicIn.getInstance())))); this.newRecordText.registerEntityModifier(new LoopEntityModifier(new SequenceEntityModifier(new RotationModifier(pulseSeconds, -PULSE_ROTATION / 4, PULSE_ROTATION / 4), new RotationModifier(pulseSeconds, PULSE_ROTATION / 4, -PULSE_ROTATION / 4)))); } @Override protected void exitScene() { // TODO Auto-generated method stub } }
maggardJosh/Tiles
src/com/lionsteel/tiles/Scenes/GameScenes/PracticeGameOverScene.java
Java
gpl-2.0
8,347
package com.dynamo2.myerp.dynamicform.dao; import java.util.Collections; import java.util.List; import javax.persistence.Query; import com.dynamo2.myerp.dynamicform.dao.entities.resultmap.FormMDStatisticsEntry; import org.springframework.stereotype.Repository; import com.dynamo2.myerp.AbstractBaseDAO; import com.dynamo2.myerp.dynamicform.dao.entities.FormMetadata; @Repository("formMetadataDAO") public class FormMetadataDAO extends AbstractBaseDAO<FormMetadata> { public FormMetadata findFormMetadataByName(String formName) { Query q = em.createNamedQuery("findFormMetadataByName"); q.setParameter(1, formName); List rst = q.getResultList(); if (rst == null || rst.isEmpty()) { return null; } return (FormMetadata) rst.get(0); } public List<FormMetadata> listAll() { Query q = em.createNamedQuery("listAll"); List rst = q.getResultList(); if (rst == null || rst.isEmpty()) { return Collections.emptyList(); } return rst; } public List<FormMetadata> listAllByCategory(String category) { Query q = em.createNamedQuery("listAllByCategory"); q.setParameter(1, category.toLowerCase()); return q.getResultList(); } public List<FormMetadata> listByParentForm(Long parentFormID) { Query q = em.createNamedQuery("listByParentForm"); q.setParameter(1, parentFormID); return q.getResultList(); } public List<FormMDStatisticsEntry> statisticsByStatus() { Query q = em.createNamedQuery("statisticsByStatus"); return q.getResultList(); } public void updateCategory(FormMetadata fm){ Query q = em.createQuery("update table form_metadata set nav_category_id=? and seq_number=? where id=?"); q.setParameter(0,fm.getNavCategoryId()); q.setParameter(1,fm.getSeqNumber()); q.setParameter(2,fm.getId()); q.executeUpdate(); } }
dynamo2/tianma
mycrm/src/main/java/com/dynamo2/myerp/dynamicform/dao/FormMetadataDAO.java
Java
gpl-2.0
1,872
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package researchpaper; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; /** * * @author aditya */ public interface MergeThreadCompleteListener { Set<MergeThread> runningThreads = new CopyOnWriteArraySet<MergeThread>(); public void notifyOnThreadComplete(MergeThread thread); public void addSource(MergeThread thread); public void removeSource(MergeThread thread); public boolean allThreadsfinished(); }
adityashah30/distributedsort
src/researchpaper/MergeThreadCompleteListener.java
Java
gpl-2.0
555
<!DOCTYPE html> <html lang="en"> <head> <link href='http://fonts.googleapis.com/css?family=Poppins:300,400,700' rel='stylesheet' type='text/css'> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>OGP Global Summit | Cumbre Global AGA | MX 2015 </title> <!-- Bootstrap --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <link href="css/cumbre.css" rel="stylesheet"> <link rel="shortcut icon" href="img/favicon32.png"> <!-- Go to www.addthis.com/dashboard to customize your tools --> <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-519eb45b260e699c" async></script> <script type="text/javascript"> //<!-- var addthis_share = { title: "Join the 2015 OGP Global Summit | Únete a la Cumbre Global 2015 | MX 2015" } //--> </script> </head> <body> <div id="top"></div> <div class="container main"> <!--MENU--> <div class="row clearfix responsive" id="cabecera"> <nav class="navbar navbar-default" role="navigation"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button> <a href="http://www.opengovpartnership.org/"><img src="img/logo.png" width="76" height="76"></a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li><a href="index.html">Home</a></li> <li class="active"><a href="agenda.html">Agenda</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">OCT 27<strong class="caret"></strong></a> <ul class="dropdown-menu"> <li><a href="cso.html">OGP-CSO</a></li> <li><a href="poc.html">OGP-PoC</a></li> </ul> </li> <li><a href="register.html">Register</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">INFO<strong class="caret"></strong></a> <ul class="dropdown-menu"> <li><a href="about.html">About</a></li> <li><a target="_blank" href="http://webapps.turycon.com.mx/eventos/2015/CUMBREGLOBAL/en/">Accommodation</a></li> <li><a href="hospitality-cdmx.html">Hospitality</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Media<strong class="caret"></strong></a> <ul class="dropdown-menu"> <li><a target="_blank" href="http://goo.gl/forms/COjyxIy5VB">Accreditations</a></li> <li><a target="_blank" href="https://docs.google.com/document/d/1UBRM0bIQpDz56Fjgi2hqn8HbrPWLoeeVQo0aaZL-OBQ/edit?usp=sharing">Spread the word</a></li> </ul> </li> <li><a class="addthis_button_facebook"><img src="img/icono-fb.png" alt="Facebook" width="20" height="20"></a></li> <li><a class="addthis_button_twitter"><img src="img/icono-tw.png" alt="Twitter" width="20" height="20"></a></li> <li><a class="addthis_button_linkedin"><img src="img/icono-in.png" alt="Linkedin" width="20" height="20"></a></li> <li><a href="index_es.html">Es</a></li> <li class="activeU"><a href="#">En</a></li> </ul> </div> </nav> </div><!-- menu --> <!-- CUERPO --> <div class="cuerpo"> <div class="row clearfix seccion secc-about2"> <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 about"> <h2>Agenda</h2> <div id="ogp"> <p><a href="img/Cumbre_agenda11_DIGITAL-MOBILE.pdf" target="_blank">Download the agenda</a></p> <a id="sched-embed" href="http://ogpsummit2015.sched.org/">View the OGP Summit schedule & directory.</a><script type="text/javascript" src="http://ogpsummit2015.sched.org/js/embed.js"></script> </div> </div> </div> </div><!-- cuerpo --> <div id="textura" class="clearfix"> <img src="img/textura.gif" class="col-xs-12 col-sm-12 col-md-12 col-lg-12"> </div> <div id="colores"> </div> <div id="pie"> <div class="pie1 responsive"> <a href="http://www.presidencia.gob.mx/" target="_blank"><img src="img/logo-mexico.gif" alt="Gobierno de la República"></a> <a href="http://www.funcionpublica.gob.mx/" target="_blank"><img src="img/logo-sfp.gif" alt="Secretaría de la Función Pública"></a> <a href="http://sre.gob.mx/" target="_blank"><img src="img/logo-sre.gif" alt="Secretaría de Relaciones Exteriores"></a> <a href="http://datos.gob.mx/" target="_blank"><img src="img/logo-mx.gif" alt="México Abierto"></a> </div> <div class="pie2 responsive"> <a href="http://inicio.ifai.org.mx/SitePages/ifai.aspx" target="_blank"><img src="img/logo-inai.gif" alt="INAI"></a> <a href="https://www.article19.org/index.php?lang=en" target="_blank"><img src="img/logo-art19.gif" alt="Article 19"></a> <a href="http://www.cidac.org/esp/index.php" target="_blank"><img src="img/logo-cidac.gif" alt="CIDAC"></a> <a href="http://www.culturaecologica.org.mx/" target="_blank"><img src="img/logo-cultura.gif" alt="Cultura Ecológica"></a> <a href="http://fundar.org.mx/" target="_blank"><img src="img/logo-fundar.gif" alt="FUNDAR"></a> </div> <div class="pie3 responsive"> <a href="http://www.gesoc.org.mx/site/" target="_blank"><img src="img/logo-gesoc.gif" alt="Gesoc A. C."></a> <a href="http://imco.org.mx/home/" target="_blank"><img src="img/logo-imc.gif" alt="IMC"></a> <a href="http://socialtic.org/" target="_blank"><img src="img/logo-socialtic.gif" alt="Social TIC"></a> <a href="http://www.tm.org.mx/" target="_blank"><img src="img/logo-transparencia.gif" alt="Transparencia Mexicana"></a> </div> <p><a href="https://docs.google.com/document/d/1rsTxFjuxSP3r9WUWkGV1CtyErsWIADgHPW4cVO0NH8E/edit" target="_blank">Call for proposals criteria</a> | <a href="terms.html">Terms and Conditions</a> | <a href="about.html">About</a></p> </div> </div> <!-- container --> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="js/bootstrap.min.js"></script> </script> </body> </html>
mxabierto/cumbre-global
agenda.html
HTML
gpl-2.0
7,264
<?php // MyDMS. Document Management System // Copyright (C) 2010 Matteo Lucarelli // // 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., 675 Mass Ave, Cambridge, MA 02139, USA. include("../inc/inc.Settings.php"); include("../inc/inc.DBInit.php"); include("../inc/inc.Utils.php"); include("../inc/inc.Language.php"); include("../inc/inc.ClassUI.php"); include("../inc/inc.Authentication.php"); if (!$user->isAdmin()) { UI::exitError(getMLText("admin_tools"),getMLText("access_denied")); } if (isset($_GET["logname"])) $logname=$_GET["logname"]; else $logname=NULL; if (isset($_GET["mode"])) $mode=$_GET["mode"]; else $mode='web'; $tmp = explode('.', basename($_SERVER['SCRIPT_FILENAME'])); $view = UI::factory($theme, $tmp[1], array('dms'=>$dms, 'user'=>$user, 'logname'=>$logname, 'mode'=>$mode, 'contentdir'=>$settings->_contentDir)); if($view) { $view->show(); exit; } ?>
JustLikeIcarus/SeedDMS
out/out.LogManagement.php
PHP
gpl-2.0
1,528
/*! \file sx9311.c * \brief SX9311 Driver * * Driver for the SX9311 * Copyright (c) 2011 Semtech Corp * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ //#define DEBUG /* for dev_dbg function */ #define DRIVER_NAME "sx9311" #define MAX_WRITE_ARRAY_SIZE 32 #include <linux/module.h> #include <linux/slab.h> #include <linux/i2c.h> #include <linux/delay.h> #include <linux/input.h> #include "sx86xx.h" /* main struct, interrupt,init,pointers */ #include "sx9311_i2c_reg.h" #include "sx9311_platform_data.h" /* platform data */ //#include <sx9500-specifics.h> #include <linux/syscalls.h> #include <linux/uaccess.h> #include <linux/sort.h> #ifdef CONFIG_OF #include <linux/regulator/consumer.h> #include <linux/of_gpio.h> #endif #if defined (CONFIG_MACH_MSM8926_T8LTE) #include <mach/board_lge.h> #endif #ifdef USE_COMMON_SYSFS #include <linux/sysdev.h> #endif #define ACTIVE 0 #define IDLE 1 #define PROX_STATUS_NEAR 0 /*ACTIVE*/ #define PROX_STATUS_FAR 1 /*IDLE*/ #define ENABLE_IRQ_MASK 0x10 #define DISABLE_IRQ_MASK 0x20 #define ENABLE_SENSOR_PINS 0x01 #define DISABLE_SENSOR_PINS 0x02 /* IO Used for NIRQ */ #define GPIO_SX9311_NIRQ 54//114 #define CS2_DISABLE 0x00 #define CS2_ENABLE 0x05 /* For Calibration & Startup function */ #define ON_SENSOR 1 #define OFF_SENSOR 2 #define COLLECT_NUM 20 #define FILTER_NUM 2 #define PATH_CAPSENSOR_CAL "/sns/capsensor_cal.dat" #define PATH_CAPSENSOR_CAL2 "/sns/capsensor_cal2.dat" #define PATH_CAL_BACKUP "/sns/capsensor_cal_backup.dat" #define SCANPERIOD_CAL 0x02 /* scanperiod 30ms[0010] */ #define PATH_XO_THERM "/sys/class/hwmon/hwmon0/device/xo_therm_pu2" #ifdef CONFIG_OF enum sensor_dt_entry_type { DT_U8, DT_U8_ARRAY, DT_U32, DT_GPIO, }; struct sensor_dt_to_platformdata { const char *dt_name; void *ptr_data; enum sensor_dt_entry_type type; }; #endif struct smtc_cal_data { s32 Calculate_CSx; s16 Useful_CSx; u16 Offset_CSx; /* fullbyte */ }; static struct _buttoninfo psmtcButtons[] = { { .keycode = KEY_0, .mask = SX9311_TCHCMPSTAT_TCHSTAT0_FLAG, }, { .keycode = KEY_1, .mask = SX9311_TCHCMPSTAT_TCHSTAT1_FLAG, }, { .keycode = KEY_2, .mask = SX9311_TCHCMPSTAT_TCHSTAT2_FLAG, }, { .keycode = KEY_3, .mask = SX9311_TCHCMPSTAT_TCHSTAT3_FLAG, }, }; static bool running_cal_or_reset = false; static bool skip_startup = false; static bool check_allnear = false; static bool on_sensor = false; typedef int (*compfn)(const void*, const void*); static int initialize_device(struct sx86XX *this); /*! \fn static int write_register(struct sx86XX *this, u8 address, u8 value) * \brief Sends a write register to the device * \param this Pointer to main parent struct * \param address 8-bit register address * \param value 8-bit register value to write to address * \return Value from i2c_master_send */ static int write_register(struct sx86XX *this, u8 address, u8 value) { struct i2c_client *i2c = NULL; /*char*/u8 buffer[2]; int returnValue = 0; buffer[0] = address; buffer[1] = value; returnValue = -ENOMEM; if (this && this->bus) { i2c = this->bus; returnValue = i2c_master_send(i2c, buffer, 2); dev_dbg(&i2c->dev, "write reg Add=0x%02x Val=0x%02x Ret=%d\n", address, value, returnValue); } return returnValue; } /*! \fn static int read_register(struct sx86XX *this, u8 address, u8 *value) * \brief Reads a register's value from the device * \param this Pointer to main parent struct * \param address 8-Bit address to read from * \param value Pointer to 8-bit value to save register value to * \return Value from i2c_smbus_read_byte_data if < 0. else 0 */ static int read_register(struct sx86XX *this, u8 address, u8 *value) { struct i2c_client *i2c = NULL; s32 returnValue = 0; if (this && value && this->bus) { i2c = this->bus; returnValue = i2c_smbus_read_byte_data(i2c, address); if (address != SX9311_IRQSTAT_REG) //temp 2014.03.24 gooni.shim dev_dbg(&i2c->dev, "read reg Add=0x%02x Ret=0x%02x\n", address, returnValue); if (returnValue >= 0) { *value = returnValue; return 0; } else { return returnValue; } } return -ENOMEM; } static void onoff_sensor(struct sx86XX *this, int onoff_mode) { struct sx9311 *pDevice = NULL; struct sx9311_platform_data *pdata = NULL; unsigned char val_regproxctrl0; unsigned char val_regirqmask; int nparse_mode; int i = 0; if (this && (pDevice = this->pDevice) && (pdata = pDevice->hw)) { while ( i < pdata->i2c_reg_num) { if (pdata->pi2c_reg[i].reg == SX9311_IRQ_ENABLE_REG) val_regirqmask = pdata->pi2c_reg[i].val; else if (pdata->pi2c_reg[i].reg == SX9311_CPS_CTRL0_REG) val_regproxctrl0 = pdata->pi2c_reg[i].val; i++; } nparse_mode = onoff_mode & ENABLE_SENSOR_PINS; dev_dbg(this->pdev, "nparse_mode=0x%02x, on_sensor=%d\n", nparse_mode, (int)on_sensor); if (nparse_mode == ENABLE_SENSOR_PINS) { write_register(this, SX9311_CPS_CTRL0_REG, val_regproxctrl0); if (!on_sensor) enable_irq_wake(this->irq); on_sensor = true; } nparse_mode = onoff_mode & DISABLE_SENSOR_PINS; if (nparse_mode == DISABLE_SENSOR_PINS) { for (i = 0; i < pDevice->pButtonInformation->buttonSize; i++) { pDevice->pButtonInformation->buttons[i].state = IDLE; } /* Clear flags because sensor is disabled. */ this->inStartupTouch = false; running_cal_or_reset = false; check_allnear = false; write_register(this, SX9311_CPS_CTRL0_REG, ((val_regproxctrl0 >> 4) << 4) | 0x00); if (on_sensor) disable_irq_wake(this->irq); on_sensor = false; } nparse_mode = onoff_mode & ENABLE_IRQ_MASK; if (nparse_mode == ENABLE_IRQ_MASK) write_register(this, SX9311_IRQ_ENABLE_REG, val_regirqmask); nparse_mode = onoff_mode & DISABLE_IRQ_MASK; if (nparse_mode == DISABLE_IRQ_MASK) write_register(this, SX9311_IRQ_ENABLE_REG, 0x00); msleep(100); /* make sure everything is running */ } } static bool valid_multiple_input_pins(struct sx86XX *this) { struct sx9311 *pDevice = NULL; struct sx9311_platform_data *pdata = NULL; if (this && (pDevice = this->pDevice) && (pdata = pDevice->hw)) { if (pdata->input_pins_num > 1) { if ((pdata->input_main2sensor >= SENSORSEL_CS0) && (pdata->input_main2sensor <= SENSORSEL_CS3) && (pdata->input_main2sensor != pdata->input_refsensor)) { return true; } } } return false; } static int write_calibration_data(struct sx86XX *this, s32 nMargin, u16 Offset_CSx, s32 TotalCap_CSx, bool isMultiInput) { int fd; int ret = 0; char buf[50]; char path_cal_file[50]; mm_segment_t old_fs = get_fs(); memset(buf, 0, sizeof(buf)); memset(path_cal_file, 0, sizeof(path_cal_file)); if (isMultiInput) strcpy(path_cal_file, PATH_CAPSENSOR_CAL2); else strcpy(path_cal_file, PATH_CAPSENSOR_CAL); sprintf(buf, "%d %d %d", nMargin, Offset_CSx, TotalCap_CSx); dev_info(this->pdev, "buf = %s\n", buf); set_fs(KERNEL_DS); fd = sys_open(path_cal_file, O_WRONLY|O_CREAT, 0664); if (fd >= 0) { sys_write(fd, buf, sizeof(buf)); sys_write(fd, "\n", 1); sys_fsync(fd); //ensure calibration data write to file system sys_close(fd); sys_chmod(path_cal_file, 0664); set_fs(old_fs); } else { ret++; sys_close(fd); set_fs(old_fs); return ret; } return ret; } static int write_calibration_backup_data(struct sx86XX *this, s32 TotalCap_CSx, s16 Useful_CSx, u16 Offset_CSx) { int fd; int ret = 0; char buf[30]; char path_cal_backup_file[50]; mm_segment_t old_fs = get_fs(); memset(buf, 0, sizeof(buf)); memset(path_cal_backup_file, 0, sizeof(path_cal_backup_file)); strcpy(path_cal_backup_file, PATH_CAL_BACKUP); sprintf(buf, "%d %d %d", TotalCap_CSx, Useful_CSx, Offset_CSx); dev_info(this->pdev, "buf = %s\n", buf); set_fs(KERNEL_DS); fd = sys_open(path_cal_backup_file, O_WRONLY|O_CREAT|O_APPEND, 0664); if (fd >= 0) { sys_write(fd, buf, sizeof(buf)); sys_write(fd, "\n", 1); sys_fsync(fd); //ensure calibration backup data write to file system sys_close(fd); sys_chmod(path_cal_backup_file, 0664); set_fs(old_fs); } else { ret++; sys_close(fd); set_fs(old_fs); return ret; } return ret; } static void read_calibration_data(struct sx86XX *this, s32 *nMargin, u16 *Offset_CSx, s32 *TotalCap_CSx, bool isMultiInput) { int fd; //int ret = 0; int len = 0; char read_buf[50]; char path_cal_file[50]; mm_segment_t old_fs = get_fs(); s32 nCalMargin = -1; s32 unOffset_CSx = 0; s32 nTotalCap_CSx = 0; *nMargin = (s32) nCalMargin; *Offset_CSx = (u16) unOffset_CSx; *TotalCap_CSx = (s32) nTotalCap_CSx; memset(read_buf, 0, sizeof(read_buf)); memset(path_cal_file, 0, sizeof(path_cal_file)); if (isMultiInput) strcpy(path_cal_file, PATH_CAPSENSOR_CAL2); else strcpy(path_cal_file, PATH_CAPSENSOR_CAL); set_fs(KERNEL_DS); fd = sys_open(path_cal_file, O_RDONLY, 0); if (fd >= 0) { len = sys_read(fd, read_buf, sizeof(read_buf)); dev_dbg(this->pdev, "cap sensor calibration file size is = %d\n", len); if (len <= 0) { //ret = -1; sys_close(fd); set_fs(old_fs); //return ret; return; } sscanf(read_buf, "%d %d %d", &nCalMargin, &unOffset_CSx, &nTotalCap_CSx); *nMargin = (s32) nCalMargin; *Offset_CSx = (u16) unOffset_CSx; *TotalCap_CSx = (s32) nTotalCap_CSx; sys_close(fd); set_fs(old_fs); } else { dev_err(this->pdev, "Read cap sensor cal data. Error[%d]!!!\n", fd); //ret = -1; sys_close(fd); set_fs(old_fs); //return ret; return; } } static void read_xo_therm_data(struct sx86XX *this, int *xo_therm) { int fd; //int ret = 0; int len = 0; char read_buf[32]; mm_segment_t old_fs = get_fs(); int nresult = 0; int nraw = 0; *xo_therm = (int) nresult; memset(read_buf, 0, sizeof(read_buf)); set_fs(KERNEL_DS); fd = sys_open(PATH_XO_THERM, O_RDONLY, 0); if (fd >= 0) { len = sys_read(fd, read_buf, sizeof(read_buf)); dev_dbg(this->pdev, "current xo_thermal data file size is = %d\n", len); if (len <= 0) { //ret = -1; sys_close(fd); set_fs(old_fs); //return ret; return; } sscanf(read_buf, "Result:%d Raw:%d\n", &nresult, &nraw); *xo_therm = (int) nresult; sys_close(fd); set_fs(old_fs); } else { dev_err(this->pdev, "Read xo_therm data. Error[%d]!!!\n", fd); //ret = -1; sys_close(fd); set_fs(old_fs); //return ret; return; } } static void read_sensor_regdata(struct sx86XX *this, unsigned char nSensorSel, s16 *pUseful_CSx, s16 *pAvg_CSx, s16 *pDiff_CSx, u16 *pOffset_CSx) { u8 msByte = 0; u8 lsByte = 0; s16 Useful_CSx = 0; s16 Avg_CSx = 0; s16 Diff_CSx = 0; u16 Offset_CSx = 0; if (this) { write_register(this, SX9311_SENSORSEL_REG, nSensorSel); read_register(this, SX9311_USEMSB_REG, &msByte); read_register(this, SX9311_USELSB_REG, &lsByte); Useful_CSx = (s16)((msByte << 8) | lsByte); msByte = 0; lsByte = 0; read_register(this, SX9311_AVGMSB_REG, &msByte); read_register(this, SX9311_AVGLSB_REG, &lsByte); Avg_CSx = (s16)((msByte << 8) | lsByte); msByte = 0; lsByte = 0; read_register(this, SX9311_DIFFMSB_REG, &msByte); read_register(this, SX9311_DIFFLSB_REG, &lsByte); Diff_CSx = (s16)((msByte << 8) | lsByte); if (Diff_CSx > 4095) Diff_CSx -= 8192; msByte = 0; lsByte = 0; read_register(this, SX9311_OFFSETMSB_REG, &msByte); read_register(this, SX9311_OFFSETLSB_REG, &lsByte); Offset_CSx = (u16)((msByte << 8) | lsByte); *pUseful_CSx = (s16) Useful_CSx; *pAvg_CSx = (s16) Avg_CSx; *pDiff_CSx = (s16) Diff_CSx; *pOffset_CSx = (u16) Offset_CSx; } return; } static void calculate_CSx_rawdata(struct sx86XX *this, unsigned char channel_num, s16 *pUseful_CSx, u16 *pOffset_CSx, s32 *pCalculate_CSx) { struct sx9311 *pDevice = NULL; struct sx9311_platform_data *pdata = NULL; u8 Byte13 = 0; u8 Byte12_6 = 0; u8 Byte5_0 = 0; u8 msByte = 0; u8 lsByte = 0; s16 Useful_CSx = 0; u16 Offset_CSx = 0; /* fullbyte */ s32 Calculate_CSx = 0; s32 ncapacitance_range = RANGE_MEDIUM_SMALL; s32 ngain_factor = GAIN_8X; if (this && (pDevice = this->pDevice) && (pdata = pDevice->hw)) { ncapacitance_range = pdata->capacitance_range; ngain_factor = pdata->gain_factor; } // Calculate out the CSx Cap information // write_register(this, SX9311_SENSORSEL_REG, channel_num); read_register(this, SX9311_USEMSB_REG, &msByte); read_register(this, SX9311_USELSB_REG, &lsByte); Useful_CSx = (s16) ((msByte << 8) | lsByte); msByte = 0; lsByte = 0; read_register(this, SX9311_OFFSETMSB_REG, &msByte); read_register(this, SX9311_OFFSETLSB_REG, &lsByte); Offset_CSx = (u16)((msByte << 8) | lsByte); Byte13 = 0; Byte12_6 = 0; Byte5_0 = 0; Byte13 = (u8)(Offset_CSx >> 13); Byte12_6 = (u8)((Offset_CSx&0x1fc0)>>6); Byte5_0 = (u8)(Offset_CSx & 0x3f); // Calculate total capacitance. // Use offset value, capacitance range, gain_factor. //Calculate_CSx = 2 * (((s32) msByte * 3600) + ((s32) lsByte * 225)) + Calculate_CSx = ((Byte13 * 234000)+(Byte12_6 * 9000)+(Byte5_0 *450)) + (((s32) Useful_CSx * ncapacitance_range) / (ngain_factor * 65536)); dev_info(this->pdev, "CS[%02x] Useful = %6d, Offset = %6d, Calculate = %6d\n", channel_num, Useful_CSx, Offset_CSx, Calculate_CSx); if (pUseful_CSx) *pUseful_CSx = (s16) Useful_CSx; if (pOffset_CSx) *pOffset_CSx = (u16) Offset_CSx; if (pCalculate_CSx) *pCalculate_CSx = (s32) Calculate_CSx; return; } /***********************************************************/ /*! \brief Perform a manual offset calibration * \param this Pointer to main parent struct * \return Value return value from the write register */ static int manual_offset_calibration(struct sx86XX *this) { s32 returnValue = 0; returnValue = write_register(this, SX9311_IRQSTAT_REG, 0xFF); return returnValue; } /*! \brief sysfs show function for manual calibration which currently just * returns register value. */ static ssize_t manual_offset_calibration_show(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); dev_dbg(this->pdev, "Reading IRQSTAT_REG\n"); read_register(this, SX9311_IRQSTAT_REG, &reg_value); return sprintf(buf, "0x%2x\n", reg_value); } /*! \brief sysfs store function for manual calibration */ static ssize_t manual_offset_calibration_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; dev_dbg( this->pdev, "Performing manual_offset_calibration()\n"); manual_offset_calibration(this); return count; } static u32 conv_regval_to_range(unsigned char regval) { unsigned char val_6bit = (((1 << 6) & regval) >> 6); unsigned char val_5bit = (((1 << 5) & regval) >> 5); unsigned char val_rangebit = ((val_6bit << 1) | val_5bit); u32 ncapacitancerange = RANGE_LARGE; switch (val_rangebit) { case REG_RANGE_LARGE: ncapacitancerange = RANGE_LARGE; break; case REG_RANGE_MEDIUM_LARGE: ncapacitancerange = RANGE_MEDIUM_LARGE; break; case REG_RANGE_MEDIUM_SMALL: ncapacitancerange = RANGE_MEDIUM_SMALL; break; case REG_RANGE_SMALL: ncapacitancerange = RANGE_SMALL; break; } return ncapacitancerange; } static u32 conv_regval_to_gain(unsigned char regval) { unsigned char val_3bit = (((1 << 3) & regval) >> 3); unsigned char val_2bit = (((1 << 2) & regval) >> 2); unsigned char val_gainbit = ((val_3bit << 1) | val_2bit); u32 ngainfactor = GAIN_1X; switch (val_gainbit) { case REG_GAIN_1X: ngainfactor = GAIN_1X; break; case REG_GAIN_2X: ngainfactor = GAIN_2X; break; case REG_GAIN_4X: ngainfactor = GAIN_4X; break; case REG_GAIN_8X: ngainfactor = GAIN_8X; break; } return ngainfactor; } static unsigned char conv_sensorsel_to_sensoren(unsigned char csx_pin) { unsigned char sensoren_csx; switch (csx_pin) { case SENSORSEL_CS0: sensoren_csx = SENSOREN_CS0; break; case SENSORSEL_CS1: sensoren_csx = SENSOREN_CS1; break; case SENSORSEL_CS2: sensoren_csx = SENSOREN_CS2; break; case SENSORSEL_CS3: sensoren_csx = SENSOREN_CS3; break; } return sensoren_csx; } static int cmp_rawdata(struct smtc_cal_data *elem1, struct smtc_cal_data *elem2) { // Ascending sort by Capacitance value. if (elem1->Calculate_CSx > elem2->Calculate_CSx) return 1; else if (elem1->Calculate_CSx < elem2->Calculate_CSx) return -1; else return 0; } static ssize_t sx9311_show_skipstartup(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "%d\n", (int) skip_startup); } static ssize_t sx9311_store_skipstartup(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; dev_dbg(this->pdev,"skipstartup set val = %d\n", (int) val); if (val == 0) skip_startup = false; else if (val == 1) skip_startup = true; return count; } static ssize_t sx9311_store_onoffsensor(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; dev_info(this->pdev,"request onoff val = %d\n", (int) val); if (val == ON_SENSOR) onoff_sensor(this, ENABLE_IRQ_MASK | ENABLE_SENSOR_PINS); else if (val == OFF_SENSOR) onoff_sensor(this, DISABLE_IRQ_MASK | DISABLE_SENSOR_PINS); return count; } static ssize_t sx9311_store_docalibration(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); struct sx9311 *pDevice = NULL; unsigned char cal_scanperiod = SCANPERIOD_CAL;// Set SCANPERIOD[6:4] - 000(30ms). unsigned char write_RegProxCtrl0 = 0x00; unsigned char mainSensor = 0; unsigned char main2Sensor = 0; unsigned char refSensor = 0; struct smtc_cal_data capMain_cal_data[COLLECT_NUM]; struct smtc_cal_data capMain2_cal_data[COLLECT_NUM]; struct smtc_cal_data capRef_cal_data[COLLECT_NUM]; s32 avg_Capacitance_Main = 0; s32 avg_Useful_Main = 0; s32 avg_Offset_Main = 0; s32 avg_Capacitance_Main2 = 0; s32 avg_Useful_Main2 = 0; s32 avg_Offset_Main2 = 0; s32 avg_Capacitance_Ref = 0; s32 avg_Useful_Ref = 0; s32 avg_Offset_Ref = 0; s32 avg_Capacitance_Ref_dynamicthreshold = 0; s32 nhysteresis = 0; s32 capMargin = 0; s32 capMargin2 = 0; bool is_different_offset = false; bool is_over_gap_useful = false; bool is_over_useful = false; int ret = 0; if (this && (pDevice = this->pDevice) && !running_cal_or_reset) { int i = 0; u8 old_RegIrqMsk_val = 0; u8 old_RegCtrl0_val = 0; unsigned char conv_mainSensor = 0; unsigned char conv_main2Sensor = 0; unsigned char conv_refSensor = 0; running_cal_or_reset = true; dev_info(this->pdev, "calibration start!!!\n"); mainSensor = (unsigned char)pDevice->hw->input_mainsensor; if (valid_multiple_input_pins(this)) main2Sensor = (unsigned char)pDevice->hw->input_main2sensor; refSensor = (unsigned char)pDevice->hw->input_refsensor; conv_mainSensor = conv_sensorsel_to_sensoren(mainSensor); if (valid_multiple_input_pins(this)) conv_main2Sensor = conv_sensorsel_to_sensoren(main2Sensor); conv_refSensor = conv_sensorsel_to_sensoren(refSensor); write_RegProxCtrl0 = (unsigned char) ((cal_scanperiod << 4) | (conv_mainSensor | conv_main2Sensor | conv_refSensor)); // Backup RegIrqMask & RegProxCtrl0 value. // And, Change RegIrqMask & RegProxCtrl0(scanperiod) value for calibration. read_register(this, SX9311_IRQ_ENABLE_REG, &old_RegIrqMsk_val); read_register(this, SX9311_CPS_CTRL0_REG, &old_RegCtrl0_val); write_register(this, SX9311_IRQ_ENABLE_REG, 0x70); write_register(this, SX9311_CPS_CTRL0_REG, write_RegProxCtrl0); msleep(100); /* make sure everything is running */ manual_offset_calibration(this); // This should cover most of the scan periods, if extremely large may // want to set this to 500 msleep(500); /* make sure manual offset has been fully done */ // Clear flags because sensor is calibrationing. this->inStartupTouch = false; check_allnear = false; // Calculate out the Cap information for Main/(Main2/)Ref Pins. for (i = 0; i < COLLECT_NUM; i++) { calculate_CSx_rawdata(this, mainSensor, &capMain_cal_data[i].Useful_CSx, &capMain_cal_data[i].Offset_CSx, &capMain_cal_data[i].Calculate_CSx); if (valid_multiple_input_pins(this)) { calculate_CSx_rawdata(this, main2Sensor, &capMain2_cal_data[i].Useful_CSx, &capMain2_cal_data[i].Offset_CSx, &capMain2_cal_data[i].Calculate_CSx); } calculate_CSx_rawdata(this, refSensor, &capRef_cal_data[i].Useful_CSx, &capRef_cal_data[i].Offset_CSx, &capRef_cal_data[i].Calculate_CSx); msleep(50); } // To sort the collected value. sort((void *) &capMain_cal_data, COLLECT_NUM, sizeof(struct smtc_cal_data), (compfn) cmp_rawdata, NULL); if (valid_multiple_input_pins(this)) { sort((void *) &capMain2_cal_data, COLLECT_NUM, sizeof(struct smtc_cal_data), (compfn) cmp_rawdata, NULL); } sort((void *) &capRef_cal_data, COLLECT_NUM, sizeof(struct smtc_cal_data), (compfn) cmp_rawdata, NULL); // Check readback sensor raw data. // 1. Check Offset value.(is equal values?) // 2. Check Useful value.(is over min/max gap? is over init range?) for (i = 0; i < COLLECT_NUM; i++) { if (capMain_cal_data[i].Offset_CSx != capMain_cal_data[COLLECT_NUM/2].Offset_CSx) { is_different_offset = true; dev_info(this->pdev, "Calibration Fail! different(offset)! [%d] %d\n", i, capMain_cal_data[i].Offset_CSx); } } if (is_different_offset == false) { if ((capMain_cal_data[COLLECT_NUM-1].Useful_CSx - capMain_cal_data[0].Useful_CSx) > 2000) { is_over_gap_useful = true; dev_info(this->pdev, "Calibration Fail! over gap(useful)! [gap = %d(%d - %d)]\n", ((capMain_cal_data[COLLECT_NUM-1].Useful_CSx) - (capMain_cal_data[0].Useful_CSx)), capMain_cal_data[COLLECT_NUM-1].Useful_CSx, capMain_cal_data[0].Useful_CSx); } for (i = 0; i < COLLECT_NUM; i++) { if ((capMain_cal_data[i].Useful_CSx < -8000) || (capMain_cal_data[i].Useful_CSx > 8000)) { is_over_useful = true; dev_info(this->pdev, "Calibration Fail! over range(useful)! [%d] %d\n", i, capMain_cal_data[i].Useful_CSx); } } } if (is_different_offset || is_over_gap_useful || is_over_useful) { ret = write_calibration_data(this, 0, 0, 0, false); //if (valid_multiple_input_pins(this)) // ret = write_calibration_data(this, 0, 0, 0, true); running_cal_or_reset = false; return count; } // Calculate the average capacitance value about the Main/(Main2/)Ref Pins. // 2 max & 2 min values are excluded. for (i = FILTER_NUM; i < COLLECT_NUM - FILTER_NUM; i++) { avg_Capacitance_Main += capMain_cal_data[i].Calculate_CSx; avg_Useful_Main += capMain_cal_data[i].Useful_CSx; avg_Offset_Main += capMain_cal_data[i].Offset_CSx; } avg_Capacitance_Main = avg_Capacitance_Main / (COLLECT_NUM - (FILTER_NUM * 2)); avg_Useful_Main = avg_Useful_Main / (COLLECT_NUM - (FILTER_NUM * 2)); avg_Offset_Main = avg_Offset_Main / (COLLECT_NUM - (FILTER_NUM * 2)); dev_info(this->pdev, "avg_Capacitance_Main = %d, avg_Useful_Main = %d, avg_Offset_Main = %d\n", avg_Capacitance_Main, avg_Useful_Main, avg_Offset_Main); if (valid_multiple_input_pins(this)) { for (i = FILTER_NUM; i < COLLECT_NUM - FILTER_NUM; i++) { avg_Capacitance_Main2 += capMain2_cal_data[i].Calculate_CSx; avg_Useful_Main2 += capMain2_cal_data[i].Useful_CSx; avg_Offset_Main2 += capMain2_cal_data[i].Offset_CSx; } avg_Capacitance_Main2 = avg_Capacitance_Main2 / (COLLECT_NUM - (FILTER_NUM * 2)); avg_Useful_Main2 = avg_Useful_Main2 / (COLLECT_NUM - (FILTER_NUM * 2)); avg_Offset_Main2 = avg_Offset_Main2 / (COLLECT_NUM - (FILTER_NUM * 2)); dev_info(this->pdev, "avg_Capacitance_Main2 = %d, avg_Useful_Main2 = %d, avg_Offset_Main2 = %d\n", avg_Capacitance_Main2, avg_Useful_Main2, avg_Offset_Main2); } for (i = FILTER_NUM; i < COLLECT_NUM - FILTER_NUM; i++) { avg_Capacitance_Ref += capRef_cal_data[i].Calculate_CSx; avg_Useful_Ref += capRef_cal_data[i].Useful_CSx; avg_Offset_Ref += capRef_cal_data[i].Offset_CSx; } avg_Capacitance_Ref = avg_Capacitance_Ref / (COLLECT_NUM - (FILTER_NUM * 2)); avg_Useful_Ref = avg_Useful_Ref / (COLLECT_NUM - (FILTER_NUM * 2)); avg_Offset_Ref = avg_Offset_Ref / (COLLECT_NUM - (FILTER_NUM * 2)); dev_info(this->pdev, "avg_Capacitance_Ref = %d, avg_Useful_Ref = %d, avg_Offset_Ref = %d\n", avg_Capacitance_Ref, avg_Useful_Ref, avg_Offset_Ref); // Calculate the dynamic thershold through the ref sensor. avg_Capacitance_Ref_dynamicthreshold = pDevice->pStartupCheckParameters->dynamicthreshold_offset + ((pDevice->pStartupCheckParameters->dynamicthreshold_temp_slope * avg_Capacitance_Ref) / 10); // Calculate capacitance margin value. // And, Save margin & offset values. nhysteresis = pDevice->pStartupCheckParameters->dynamicthreshold_hysteresis; capMargin = avg_Capacitance_Main - avg_Capacitance_Ref_dynamicthreshold + nhysteresis; ret = write_calibration_data(this, capMargin, capMain_cal_data[COLLECT_NUM/2].Offset_CSx, avg_Capacitance_Main, false); if (valid_multiple_input_pins(this)) { capMargin2 = avg_Capacitance_Main2 - avg_Capacitance_Ref_dynamicthreshold + nhysteresis; ret = write_calibration_data(this, capMargin2, capMain2_cal_data[COLLECT_NUM/2].Offset_CSx, avg_Capacitance_Main2, true); } write_calibration_backup_data(this, avg_Capacitance_Main, (s16) avg_Useful_Main, (u16) avg_Offset_Main); if (valid_multiple_input_pins(this)) { write_calibration_backup_data(this, avg_Capacitance_Main2, (s16)avg_Useful_Main2, (u16) avg_Offset_Main2); } write_calibration_backup_data(this, avg_Capacitance_Ref, (s16) avg_Useful_Ref, (u16) avg_Offset_Ref); // Restore RegIrqMask & RegProxCtrl0(scanperiod) value. write_register(this, SX9311_IRQ_ENABLE_REG, old_RegIrqMsk_val); write_register(this, SX9311_CPS_CTRL0_REG, old_RegCtrl0_val); // Must be sure to set the Main CS pin. write_register(this, SX9311_SENSORSEL_REG, mainSensor); dev_info(this->pdev, "calibration end!!!\n"); running_cal_or_reset = false; } return count; } static ssize_t sx9311_store_checkallnear(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; dev_info(this->pdev,"checkallnear set val = %d\n", (int) val); if (val == 0) check_allnear = false; else if (val == 1) check_allnear = true; return count; } static ssize_t sx9311_show_count_inputpins(struct device *dev, struct device_attribute *attr, char *buf) { int count_inputpins = 0; struct sx86XX *this = dev_get_drvdata(dev); struct sx9311 *pDevice = NULL; struct sx9311_platform_data *pdata = NULL; if (this && (pDevice = this->pDevice) && (pdata = pDevice->hw)) { count_inputpins = pdata->input_pins_num; if (count_inputpins > 1) { if (valid_multiple_input_pins(this) == false) count_inputpins = 1; } } dev_info(this->pdev,"count input pins = %d\n", count_inputpins); return sprintf(buf, "%d\n", count_inputpins); } static ssize_t sx9311_show_proxstatus(struct device *dev, struct device_attribute *attr, char *buf) { struct sx9311 *pDevice = NULL; struct sx86XX *this = dev_get_drvdata(dev); struct _buttoninfo *buttons = NULL; u8 mainSensor, main2Sensor; int prox_status = -1; if (this && (pDevice = this->pDevice)) { buttons = pDevice->pButtonInformation->buttons; mainSensor = pDevice->hw->input_mainsensor; if (valid_multiple_input_pins(this)) { main2Sensor = pDevice->hw->input_main2sensor; if (check_allnear) { if ((buttons[mainSensor].state == IDLE) || (buttons[main2Sensor].state == IDLE)) prox_status = IDLE; if ((buttons[mainSensor].state == ACTIVE) && (buttons[main2Sensor].state == ACTIVE)) prox_status = ACTIVE; } else { if ((buttons[mainSensor].state == IDLE) && (buttons[main2Sensor].state == IDLE)) prox_status = IDLE; if ((buttons[mainSensor].state == ACTIVE) || (buttons[main2Sensor].state == ACTIVE)) prox_status = ACTIVE; } } else { prox_status = buttons[mainSensor].state; } } return sprintf(buf, "%d\n", prox_status); } static ssize_t sx9311_show_regproxdata(struct device *dev, struct device_attribute *attr, char *buf) { s16 main_Useful = 0, main_Avg = 0, main_Diff = 0; u16 main_Offset = 0; s16 main2_Useful = 0, main2_Avg = 0, main2_Diff = 0; u16 main2_Offset = 0; s16 ref_Useful = 0, ref_Avg = 0, ref_Diff = 0; u16 ref_Offset = 0; u8 mainSensor, main2Sensor, refSensor; int current_xo_therm = 0; char buf_bstate_main[5] = ""; char buf_bstate_main2[5] = ""; char buf_line[64] = ""; char buf_regproxdata[256] = ""; int nlength = 0; struct sx9311 *pDevice = NULL; struct sx86XX *this = dev_get_drvdata(dev); struct _buttoninfo *buttons = NULL; memset(buf_bstate_main, 0, sizeof(buf_bstate_main)); memset(buf_bstate_main2, 0, sizeof(buf_bstate_main2)); memset(buf_line, 0, sizeof(buf_line)); memset(buf_regproxdata, 0, sizeof(buf_regproxdata)); if (this && (pDevice = this->pDevice) && !running_cal_or_reset) { buttons = pDevice->pButtonInformation->buttons; // Select Main Sensor, Readback Reg Sensor Data mainSensor = pDevice->hw->input_mainsensor; read_sensor_regdata(this, mainSensor, &main_Useful, &main_Avg, &main_Diff, &main_Offset); (buttons[mainSensor].state) ? strcpy(buf_bstate_main, "F"):strcpy(buf_bstate_main, "N"); dev_info(this->pdev,"capMain = %6d %6d %6d %6d %s\n", main_Useful, main_Avg, main_Diff, main_Offset, buf_bstate_main); // Select Main2 Sensor, Readback Reg Sensor Data if (valid_multiple_input_pins(this)) { main2Sensor = pDevice->hw->input_main2sensor; read_sensor_regdata(this, main2Sensor, &main2_Useful, &main2_Avg, &main2_Diff, &main2_Offset); (buttons[main2Sensor].state) ? strcpy(buf_bstate_main2, "F"):strcpy(buf_bstate_main2, "N"); dev_info(this->pdev,"capMain2 = %6d %6d %6d %6d %s\n", main2_Useful, main2_Avg, main2_Diff, main2_Offset, buf_bstate_main2); } // Select Reference Sensor, Readback Reg Sensor Data refSensor = pDevice->hw->input_refsensor; read_sensor_regdata(this, refSensor, &ref_Useful, &ref_Avg, &ref_Diff, &ref_Offset); dev_info(this->pdev,"capRef = %6d %6d %6d %6d\n", ref_Useful, ref_Avg, ref_Diff, ref_Offset); // Please Select Main Sensor again. write_register(this, SX9311_SENSORSEL_REG, mainSensor); read_xo_therm_data(this, &current_xo_therm); } sprintf(buf_line, "[M]%6d %6d %6d %6d %s %3d\n", main_Useful, main_Avg, main_Diff, main_Offset, buf_bstate_main, current_xo_therm); strcpy(buf_regproxdata, buf_line); if (this && valid_multiple_input_pins(this)) { sprintf(buf_line, "[S]%6d %6d %6d %6d %s\n", main2_Useful, main2_Avg, main2_Diff, main2_Offset, buf_bstate_main2); nlength = strlen(buf_regproxdata); strcpy(&buf_regproxdata[nlength], buf_line); } sprintf(buf_line, "[R]%6d %6d %6d %6d\n", ref_Useful, ref_Avg, ref_Diff, ref_Offset); nlength = strlen(buf_regproxdata); strcpy(&buf_regproxdata[nlength], buf_line); return sprintf(buf, "%s", buf_regproxdata); } static ssize_t sx9311_show_regproxctrl0(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_CPS_CTRL0_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regproxctrl0(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx9311 *pDevice = NULL; struct sx86XX *this = dev_get_drvdata(dev); struct input_dev *input = NULL; unsigned long val; unsigned long val_check; int i = 0; int ret = 0; if (strict_strtoul(buf, 0, &val)) return -EINVAL; ret = write_register(this, SX9311_CPS_CTRL0_REG, val); if (ret > 0) { val_check = val & SENSOREN_CS2; if (val_check == SENSOREN_DISABLE_ALL) { /* Initialize prox status : default FAR */ if (this && (pDevice = this->pDevice)) { for (i = 0; i < pDevice->pButtonInformation->buttonSize; i++) { pDevice->pButtonInformation->buttons[i].state = IDLE; } input = pDevice->pButtonInformation->input; input_report_abs(input, ABS_DISTANCE, PROX_STATUS_FAR); input_sync(input); } } } return count; } static ssize_t sx9311_show_regproxctrl1(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_CPS_CTRL1_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regproxctrl1(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; write_register(this, SX9311_CPS_CTRL1_REG, val); return count; } static ssize_t sx9311_show_regproxctrl2(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_CPS_CTRL2_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regproxctrl2(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; write_register(this, SX9311_CPS_CTRL2_REG, val); return count; } static ssize_t sx9311_show_regproxctrl3(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_CPS_CTRL3_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regproxctrl3(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; write_register(this, SX9311_CPS_CTRL3_REG, val); return count; } static ssize_t sx9311_show_regproxctrl4(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_CPS_CTRL4_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regproxctrl4(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; write_register(this, SX9311_CPS_CTRL4_REG, val); return count; } static ssize_t sx9311_show_regproxctrl5(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_CPS_CTRL5_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regproxctrl5(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; write_register(this, SX9311_CPS_CTRL5_REG, val); return count; } static ssize_t sx9311_show_regproxctrl6(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_CPS_CTRL6_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regproxctrl6(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; write_register(this, SX9311_CPS_CTRL6_REG, val); return count; } static ssize_t sx9311_show_regproxctrl7(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_CPS_CTRL7_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regproxctrl7(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; write_register(this, SX9311_CPS_CTRL7_REG, val); return count; } static ssize_t sx9311_show_regproxctrl8(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_CPS_CTRL8_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regproxctrl8(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; write_register(this, SX9311_CPS_CTRL8_REG, val); return count; } static ssize_t sx9311_show_regproxctrl9(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_CPS_CTRL9_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regproxctrl9(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; write_register(this, SX9311_CPS_CTRL9_REG, val); return count; } static ssize_t sx9311_show_regproxctrl10(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_CPS_CTRL10_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regproxctrl10(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; write_register(this, SX9311_CPS_CTRL10_REG, val); return count; } static ssize_t sx9311_show_regproxctrl11(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_CPS_CTRL11_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regproxctrl11(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; write_register(this, SX9311_CPS_CTRL11_REG, val); return count; } static ssize_t sx9311_show_regproxctrl12(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_CPS_CTRL12_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regproxctrl12(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; write_register(this, SX9311_CPS_CTRL12_REG, val); return count; } static ssize_t sx9311_show_regproxctrl13(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_CPS_CTRL13_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regproxctrl13(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; write_register(this, SX9311_CPS_CTRL13_REG, val); return count; } static ssize_t sx9311_show_regproxctrl14(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_CPS_CTRL14_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regproxctrl14(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; write_register(this, SX9311_CPS_CTRL14_REG, val); return count; } static ssize_t sx9311_show_regproxctrl15(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_CPS_CTRL15_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regproxctrl15(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; write_register(this, SX9311_CPS_CTRL15_REG, val); return count; } static ssize_t sx9311_show_regproxctrl16(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_CPS_CTRL16_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regproxctrl16(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; write_register(this, SX9311_CPS_CTRL16_REG, val); return count; } static ssize_t sx9311_show_regproxctrl17(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_CPS_CTRL17_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regproxctrl17(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; write_register(this, SX9311_CPS_CTRL17_REG, val); return count; } static ssize_t sx9311_show_regproxctrl18(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_CPS_CTRL18_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regproxctrl18(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; write_register(this, SX9311_CPS_CTRL18_REG, val); return count; } static ssize_t sx9311_show_regproxctrl19(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_CPS_CTRL19_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regproxctrl19(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; write_register(this, SX9311_CPS_CTRL19_REG, val); return count; } static ssize_t sx9311_show_regsarctrl0(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_CPS_SAR_CTRL0_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regsarctrl0(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; write_register(this, SX9311_CPS_SAR_CTRL0_REG, val); return count; } static ssize_t sx9311_show_regsarctrl1(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_CPS_SAR_CTRL1_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regsarctrl1(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; write_register(this, SX9311_CPS_SAR_CTRL1_REG, val); return count; } static ssize_t sx9311_show_regsarctrl2(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_CPS_SAR_CTRL2_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regsarctrl2(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; write_register(this, SX9311_CPS_SAR_CTRL2_REG, val); return count; } static ssize_t sx9311_show_regirqmask(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_IRQ_ENABLE_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regirqmask(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; write_register(this, SX9311_IRQ_ENABLE_REG, val); return count; } static ssize_t sx9311_store_regreset(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx9311 *pDevice = NULL; struct sx86XX *this = dev_get_drvdata(dev); struct input_dev *input = NULL; unsigned long val; int i = 0; if (strict_strtoul(buf, 0, &val)) return -EINVAL; if (this && (pDevice = this->pDevice) && !running_cal_or_reset) { running_cal_or_reset = true; if (val == SX9311_SOFTRESET) { dev_info(this->pdev, "reset start!!!\n"); for (i = 0; i < pDevice->pButtonInformation->buttonSize; i++) { pDevice->pButtonInformation->buttons[i].state = IDLE; } input = pDevice->pButtonInformation->input; input_report_abs(input, ABS_DISTANCE, PROX_STATUS_FAR); input_sync(input); //sx86XX_suspend(this); //sx86XX_resume(this); //disable_irq(this->irq); #ifdef USE_THREADED_IRQ mutex_lock(&this->mutex); /* Just in case need to reset any uncaught interrupts */ sx86XX_process_interrupt(this,0); mutex_unlock(&this->mutex); #else sx86XX_schedule_work(this,0); #endif initialize_device(this); //enable_irq(this->irq); dev_info(this->pdev, "reset end!!!\n"); } running_cal_or_reset = false; } return count; } static ssize_t sx9311_store_regoffset(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned int msb_val; unsigned int lsb_val; if (sscanf(buf, "%02x,%02x", &msb_val, &lsb_val) != 2) return -EINVAL; dev_dbg(this->pdev, "regoffset = %02x, %02x\n", msb_val, lsb_val); write_register(this, SX9311_OFFSETMSB_REG, msb_val); write_register(this, SX9311_OFFSETLSB_REG, lsb_val); return count; } static ssize_t sx9311_show_regirqsrc(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_IRQSTAT_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_show_regirqfunc(struct device *dev, struct device_attribute *attr, char *buf) { u8 reg_value = 0; struct sx86XX *this = dev_get_drvdata(dev); read_register(this, SX9311_IRQFUNC_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t sx9311_store_regirqfunc(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct sx86XX *this = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; write_register(this, SX9311_IRQFUNC_REG, val); return count; } static DEVICE_ATTR(calibrate, 0664, manual_offset_calibration_show, manual_offset_calibration_store); static DEVICE_ATTR(skipstartup, 0664, sx9311_show_skipstartup, sx9311_store_skipstartup); static DEVICE_ATTR(onoff, 0664, NULL, sx9311_store_onoffsensor); static DEVICE_ATTR(docalibration,0664, NULL, sx9311_store_docalibration); static DEVICE_ATTR(checkallnear, 0664, NULL, sx9311_store_checkallnear); static DEVICE_ATTR(cntinputpins, 0664, sx9311_show_count_inputpins, NULL); static DEVICE_ATTR(proxstatus, 0664, sx9311_show_proxstatus, NULL); static DEVICE_ATTR(regproxdata, 0664, sx9311_show_regproxdata, NULL); static DEVICE_ATTR(regproxctrl0, 0664, sx9311_show_regproxctrl0, sx9311_store_regproxctrl0); static DEVICE_ATTR(regproxctrl1, 0664, sx9311_show_regproxctrl1, sx9311_store_regproxctrl1); static DEVICE_ATTR(regproxctrl2, 0664, sx9311_show_regproxctrl2, sx9311_store_regproxctrl2); static DEVICE_ATTR(regproxctrl3, 0664, sx9311_show_regproxctrl3, sx9311_store_regproxctrl3); static DEVICE_ATTR(regproxctrl4, 0664, sx9311_show_regproxctrl4, sx9311_store_regproxctrl4); static DEVICE_ATTR(regproxctrl5, 0664, sx9311_show_regproxctrl5, sx9311_store_regproxctrl5); static DEVICE_ATTR(regproxctrl6, 0664, sx9311_show_regproxctrl6, sx9311_store_regproxctrl6); static DEVICE_ATTR(regproxctrl7, 0664, sx9311_show_regproxctrl7, sx9311_store_regproxctrl7); static DEVICE_ATTR(regproxctrl8, 0664, sx9311_show_regproxctrl8, sx9311_store_regproxctrl8); static DEVICE_ATTR(regproxctrl9, 0664, sx9311_show_regproxctrl9, sx9311_store_regproxctrl9); static DEVICE_ATTR(regproxctrl10, 0664, sx9311_show_regproxctrl10, sx9311_store_regproxctrl10); static DEVICE_ATTR(regproxctrl11, 0664, sx9311_show_regproxctrl11, sx9311_store_regproxctrl11); static DEVICE_ATTR(regproxctrl12, 0664, sx9311_show_regproxctrl12, sx9311_store_regproxctrl12); static DEVICE_ATTR(regproxctrl13, 0664, sx9311_show_regproxctrl13, sx9311_store_regproxctrl13); static DEVICE_ATTR(regproxctrl14, 0664, sx9311_show_regproxctrl14, sx9311_store_regproxctrl14); static DEVICE_ATTR(regproxctrl15, 0664, sx9311_show_regproxctrl15, sx9311_store_regproxctrl15); static DEVICE_ATTR(regproxctrl16, 0664, sx9311_show_regproxctrl16, sx9311_store_regproxctrl16); static DEVICE_ATTR(regproxctrl17, 0664, sx9311_show_regproxctrl17, sx9311_store_regproxctrl17); static DEVICE_ATTR(regproxctrl18, 0664, sx9311_show_regproxctrl18, sx9311_store_regproxctrl18); static DEVICE_ATTR(regproxctrl19, 0664, sx9311_show_regproxctrl19, sx9311_store_regproxctrl19); static DEVICE_ATTR(regsarctrl0, 0664, sx9311_show_regsarctrl0, sx9311_store_regsarctrl0); static DEVICE_ATTR(regsarctrl1, 0664, sx9311_show_regsarctrl1, sx9311_store_regsarctrl1); static DEVICE_ATTR(regsarctrl2, 0664, sx9311_show_regsarctrl2, sx9311_store_regsarctrl2); static DEVICE_ATTR(regirqmask, 0664, sx9311_show_regirqmask, sx9311_store_regirqmask); static DEVICE_ATTR(regreset, 0664, NULL, sx9311_store_regreset); static DEVICE_ATTR(regoffset, 0664, NULL, sx9311_store_regoffset); static DEVICE_ATTR(regirqsrc, 0664, sx9311_show_regirqsrc, NULL);//irq static DEVICE_ATTR(regirqfunc, 0664, sx9311_show_regirqfunc, sx9311_store_regirqfunc);//irqfunc static struct attribute *sx9311_attributes[] = { &dev_attr_calibrate.attr, &dev_attr_skipstartup.attr, &dev_attr_onoff.attr, &dev_attr_docalibration.attr, &dev_attr_checkallnear.attr, &dev_attr_cntinputpins.attr, &dev_attr_proxstatus.attr, &dev_attr_regproxdata.attr, &dev_attr_regproxctrl0.attr, &dev_attr_regproxctrl1.attr, &dev_attr_regproxctrl2.attr, &dev_attr_regproxctrl3.attr, &dev_attr_regproxctrl4.attr, &dev_attr_regproxctrl5.attr, &dev_attr_regproxctrl6.attr, &dev_attr_regproxctrl7.attr, &dev_attr_regproxctrl8.attr, &dev_attr_regproxctrl9.attr, &dev_attr_regproxctrl10.attr, &dev_attr_regproxctrl11.attr, &dev_attr_regproxctrl12.attr, &dev_attr_regproxctrl13.attr, &dev_attr_regproxctrl14.attr, &dev_attr_regproxctrl15.attr, &dev_attr_regproxctrl16.attr, &dev_attr_regproxctrl17.attr, &dev_attr_regproxctrl18.attr, &dev_attr_regproxctrl19.attr, &dev_attr_regsarctrl0.attr, &dev_attr_regsarctrl1.attr, &dev_attr_regsarctrl2.attr, &dev_attr_regirqmask.attr, &dev_attr_regreset.attr, &dev_attr_regoffset.attr, &dev_attr_regirqsrc.attr, &dev_attr_regirqfunc.attr, NULL, }; static struct attribute_group sx9311_attr_group = { .attrs = sx9311_attributes, }; /*********************************************************************/ /*! \fn static int read_regIrqStat(struct sx86XX *this) * \brief Shortcut to read what caused interrupt. * \details This is to keep the drivers a unified * function that will read whatever register(s) * provide information on why the interrupt was caused. * \param this Pointer to main parent struct * \return If successful, Value of bit(s) that cause interrupt, else 0 */ static int read_regIrqStat(struct sx86XX *this) { u8 data = 0; if (this) { if (read_register(this, SX9311_IRQSTAT_REG, &data) == 0){ dev_info(this->pdev, "SX9311_IRQSTAT_REG[0x00] = 0x%02x\n", data); return (data & 0x00FF); } } return 0; } /*! \brief Initialize I2C config from platform data * \param this Pointer to main parent struct */ static void hw_init(struct sx86XX *this) { struct sx9311 *pDevice = NULL; struct sx9311_platform_data *pdata = NULL; int i = 0; /* configure device */ dev_dbg(this->pdev, "Setup I2C Registers\n"); if (this && (pDevice = this->pDevice) && (pdata = pDevice->hw)) { while ( i < pdata->i2c_reg_num) { /* Write all registers/values contained in i2c_reg */ dev_dbg(this->pdev, "Write Reg: 0x%02x, Value: 0x%02x\n", pdata->pi2c_reg[i].reg,pdata->pi2c_reg[i].val); //msleep(3); write_register(this, pdata->pi2c_reg[i].reg,pdata->pi2c_reg[i].val); i++; } } else { dev_err(this->pdev, "ERROR! platform data 0x%p\n", pDevice->hw); } } /*********************************************************************/ /*! \fn static int initialize_device(struct sx86XX *this) * \brief Performs all initialization needed to configure the device * \param this Pointer to main parent struct * \return Last used command's return value (negative if error) */ static int initialize_device(struct sx86XX *this) { s16 Useful_CSx = 0, Avg_CSx = 0, Diff_CSx = 0; u16 Offset_CSx = 0; unsigned char mainSensor = 0x00, main2Sensor = 0x00, refSensor = 0x00; int cnt= 0; struct sx9311 *pDevice = NULL; if (this) { int i = 0; /* Make sure we initialize that we are not in startup detection */ this->inStartupTouch = false; /* prepare reset by disabling any irq handling */ this->irq_disabled = 1; disable_irq(this->irq); /* perform a reset */ write_register(this, SX9311_SOFTRESET_REG, SX9311_SOFTRESET); /* wait until the reset has finished by monitoring NIRQ */ dev_info(this->pdev, "Sent Software Reset. Waiting until device is back from reset to continue.\n"); /* just sleep for awhile instead of using a loop with reading irq status */ do { msleep(100); read_regIrqStat(this); if (++cnt >= 3) break; } while(this->get_nirq_low && this->get_nirq_low()); dev_info(this->pdev, "Device is back from the reset, continuing. NIRQ = %d\n", this->get_nirq_low()); hw_init(this); /* make sure everything is running */ msleep(100); manual_offset_calibration(this); // This should cover most of the scan periods, if extremely large may // want to set this to 500ms. Make sure manual offset has been fully done msleep(500); if (likely((pDevice = this->pDevice) != NULL)) { mainSensor = (unsigned char) pDevice->hw->input_mainsensor; refSensor = (unsigned char) pDevice->hw->input_refsensor; if (valid_multiple_input_pins(this)) main2Sensor = (unsigned char) pDevice->hw->input_main2sensor; for (i = 0; i < 5 ; i++) { read_sensor_regdata(this, mainSensor, &Useful_CSx, &Avg_CSx, &Diff_CSx, &Offset_CSx); dev_info(this->pdev, "[startup] capMain[%d] = %6d %6d %6d %6d\n", i, Useful_CSx, Avg_CSx, Diff_CSx, Offset_CSx); } if (valid_multiple_input_pins(this)) { Useful_CSx = 0, Avg_CSx = 0, Diff_CSx = 0; Offset_CSx = 0; for (i = 0; i < 5 ; i++) { read_sensor_regdata(this, main2Sensor, &Useful_CSx, &Avg_CSx, &Diff_CSx, &Offset_CSx); dev_info(this->pdev, "[startup] capMain2[%d] = %6d %6d %6d %6d\n", i, Useful_CSx, Avg_CSx, Diff_CSx, Offset_CSx); } } StartupTouchCheckWithReferenceSensor(this, mainSensor, refSensor); /* Howevet use multiple inputs, the startup is only one input is used. (Temporary Exception Handling) */ //if (valid_multiple_input_pins(this)) // StartupTouchCheckWithReferenceSensor(this, main2Sensor, refSensor); } else { dev_err(this->pdev, "Couldn't open platform data containing main and ref sensors, using fallback\n"); return -ENOMEM; } /* re-enable interrupt handling */ enable_irq(this->irq); this->irq_disabled = 0; /* make sure no interrupts are pending since enabling irq will only * work on next falling edge */ read_regIrqStat(this); dev_info(this->pdev, "Exiting initialize(). NIRQ = %d\n", this->get_nirq_low()); return 0; } return -ENOMEM; } /*! * \brief Check if a touch(near) is on the specified mainSensor * \details This uses a reference sensor (refSensor) to check whether a touch * (=near) is being performed. You normally would use this type of check * after a compensation has been made (especially during power up). * \param this Pointer to main parent struct * \param mainSensor Main sensor that may or may not have a touch * \param refSensor A known sensor that will never have a touch * \return Whether a touch was detected */ void StartupTouchCheckWithReferenceSensor(struct sx86XX *this, unsigned char mainSensor, unsigned char refSensor) { s32 cal_Margin = -65535; u16 cal_Offset = 0; /* fullbyte */ s32 cal_TotalCap = 0; s32 capMain = 0; s32 capRef = 0; s32 capStartup = 0; int counter = 0; u8 CompareButtonMask = 0; int numberOfButtons = 0; struct sx9311 *pDevice = NULL; struct _buttoninfo *buttons = NULL; struct input_dev *input = NULL; struct _buttoninfo *pCurrentButton = NULL; u8 ucTouchAvgThresh = 0; u8 ucReleaseAvgThresh = 0; u8 tempRegData = 0; if (unlikely((this==NULL) || ((pDevice = this->pDevice)==NULL))) return; // ERROR!! if (mainSensor == (pDevice->hw->input_mainsensor)) read_calibration_data(this, &cal_Margin, &cal_Offset, &cal_TotalCap, false); else if (mainSensor == (pDevice->hw->input_main2sensor)) read_calibration_data(this, &cal_Margin, &cal_Offset, &cal_TotalCap, true); dev_info(this->pdev, "read_calibration_data : %d, %d, %d\n", cal_Margin, cal_Offset, cal_TotalCap); if (skip_startup == true) return; if (cal_Margin == -65535 || cal_Offset < 500) { dev_err(this->pdev, "Fail!!! Check Calibration Data!!!\n"); return; } pDevice->pStartupCheckParameters->calibration_margin = cal_Margin; // Calculate out the Main Cap information // calculate_CSx_rawdata(this, mainSensor, NULL, NULL, &capMain); // Calculate out the Reference Cap information // calculate_CSx_rawdata(this, refSensor, NULL, NULL, &capRef); // Calculate Dynamic Threshold value. capStartup = pDevice->pStartupCheckParameters->dynamicthreshold_offset + ((pDevice->pStartupCheckParameters->dynamicthreshold_temp_slope * capRef) / 10) + pDevice->pStartupCheckParameters->calibration_margin; dev_info(this->pdev, "Main[%ld] - Startup[%ld] = %ld", (long int) capMain, (long int) capStartup, (long int) (capMain - capStartup)); // Must be sure to set the Main CS pin. write_register(this, SX9311_SENSORSEL_REG, mainSensor); // capMain is now the diff to check with startupThreshold.. // The code below is what will send the key event. // We need to shift 4 more as the lower bits are the compensation. // TODO: Change this to use a define index CompareButtonMask = 1 << (mainSensor + 0); buttons = pDevice->pButtonInformation->buttons; input = pDevice->pButtonInformation->input; numberOfButtons = pDevice->pButtonInformation->buttonSize; if (unlikely( (buttons==NULL) || (input==NULL) )) { dev_err(this->pdev, "ERROR!! buttons or input NULL!!!\n"); return; } ucTouchAvgThresh = pDevice->pStartupCheckParameters->startup_touch_regavgthresh; ucReleaseAvgThresh = pDevice->pStartupCheckParameters->startup_release_regavgthresh; // If the buttons are added to the array from 0 to max sensor, // then we could just skip the for and change this to have.. // pCurrentButton = &buttons[mainSensor] // But since they could be added out of here this is here just in case.. for (counter = 0; counter < numberOfButtons; counter++) { pCurrentButton = &buttons[counter]; if (pCurrentButton==NULL) { dev_err(this->pdev, "ERROR!! current button at index: %d NULL!!!\n", counter); return; // ERRORR!!!! } if ((CompareButtonMask & pCurrentButton->mask) != pCurrentButton->mask) { dev_dbg(this->pdev, "Mask: 0x%02x Looking For: 0x%02x Counter: %d\n", pCurrentButton->mask, CompareButtonMask, counter); continue; // Not the correct one so continue to next } switch (pCurrentButton->state) { case IDLE: /* Button is not being touched! */ if (capMain > capStartup) { /* User pressed button */ dev_info(this->pdev, "[startup]cap button %d touched\n", counter); //input_report_key(input, pCurrentButton->keycode, 1); input_report_abs(input, ABS_DISTANCE, PROX_STATUS_NEAR); input_sync(input); pCurrentButton->state = ACTIVE; /* Set the flag since touch is detected during startup */ this->inStartupTouch = true; read_register(this, SX9311_CPS_CTRL6_REG, &tempRegData); tempRegData = tempRegData & 0xc0; tempRegData = tempRegData | ucTouchAvgThresh; write_register(this, SX9311_CPS_CTRL6_REG, tempRegData); } else { /* Clear the flag since no touch is detected during startup */ this->inStartupTouch = false; read_register(this, SX9311_CPS_CTRL6_REG, &tempRegData); tempRegData = tempRegData & 0xc0; tempRegData = tempRegData | ucReleaseAvgThresh; write_register(this, SX9311_CPS_CTRL6_REG, tempRegData); dev_info(this->pdev, "[startup]Button %d already released.\n",counter); } break; case ACTIVE: /* Button is being touched! */ if (capMain <= capStartup) { /* User released button */ dev_info(this->pdev, "[startup]cap button %d released\n",counter); //input_report_key(input, pCurrentButton->keycode, 0); input_report_abs(input, ABS_DISTANCE, PROX_STATUS_FAR); input_sync(input); pCurrentButton->state = IDLE; /* Clear the flag since no touch is detected during startup */ this->inStartupTouch = false; read_register(this, SX9311_CPS_CTRL6_REG, &tempRegData); tempRegData = tempRegData & 0xc0; tempRegData = tempRegData | ucReleaseAvgThresh; write_register(this, SX9311_CPS_CTRL6_REG, tempRegData); } else { /* Set the flag since touch is detected during startup */ this->inStartupTouch = true; read_register(this, SX9311_CPS_CTRL6_REG, &tempRegData); tempRegData = tempRegData & 0xc0; tempRegData = tempRegData | ucTouchAvgThresh; write_register(this, SX9311_CPS_CTRL6_REG, tempRegData); dev_info(this->pdev, "[startup]Button %d still touched.\n",counter); } break; default: /* Shouldn't be here, device only allowed ACTIVE or IDLE */ dev_err(this->pdev, "ERROR! state: %d unknown!\n",pCurrentButton->state); break; }; break; // We only want to do this once as we only are checking one sensor } } /*! * \brief Handle what to do when a Close/Far occurs * \param this Pointer to main parent struct */ static void Irq_Process_Close_Far(struct sx86XX *this) { int counter = 0; u8 regstat = 0; int numberOfButtons = 0; struct sx9311 *pDevice = NULL; struct _buttoninfo *buttons = NULL; struct input_dev *input = NULL; struct _buttoninfo *pCurrentButton = NULL; u8 mainSensor = 0, main2Sensor = 0; if (this && (pDevice = this->pDevice)) { dev_dbg(this->pdev, "Inside Irq_Process_Close_Far()\n"); read_register(this, SX9311_TCHCMPSTAT_REG, &regstat); dev_info(this->pdev, "SX9311_TCHCMPSTAT_REG[0x01] = 0x%02x\n", regstat); buttons = pDevice->pButtonInformation->buttons; input = pDevice->pButtonInformation->input; numberOfButtons = pDevice->pButtonInformation->buttonSize; if (unlikely((buttons == NULL) || (input == NULL))) { dev_err(this->pdev, "ERROR!! buttons or input NULL!!!\n"); return; } mainSensor = pDevice->hw->input_mainsensor; if (valid_multiple_input_pins(this)) main2Sensor = pDevice->hw->input_main2sensor; for (counter = 0; counter < numberOfButtons; counter++) { pCurrentButton = &buttons[counter]; if (pCurrentButton == NULL) { dev_err(this->pdev, "ERROR!! current button at index: %d NULL!!!\n", counter); return; // ERRORR!!!! } switch (pCurrentButton->state) { case IDLE: /* Button is not being touched! */ if (((regstat & pCurrentButton->mask) == pCurrentButton->mask)) { /* User pressed button */ dev_info(this->pdev, "cap button %d touched\n", counter); /*input_report_key(input, pCurrentButton->keycode, 1);*/ if (valid_multiple_input_pins(this)) { if ((buttons[mainSensor].state == ACTIVE) || (buttons[main2Sensor].state == ACTIVE)) { pCurrentButton->state = ACTIVE; dev_info(this->pdev, "active set only\n"); } else { pCurrentButton->state = ACTIVE; input_report_abs(input, ABS_DISTANCE, PROX_STATUS_NEAR); input_sync(input); dev_info(this->pdev, "active set and PROX_STATUS_NEAR\n"); } } else { input_report_abs(input, ABS_DISTANCE, PROX_STATUS_NEAR); input_sync(input); pCurrentButton->state = ACTIVE; } } else { dev_info(this->pdev, "Button %d already released.\n",counter); } break; case ACTIVE: /* Button is being touched! */ if (((regstat & pCurrentButton->mask) != pCurrentButton->mask)) { /* User released button */ dev_info(this->pdev, "cap button %d released\n",counter); /*input_report_key(input, pCurrentButton->keycode, 0);*/ if (valid_multiple_input_pins(this)) { pCurrentButton->state = IDLE; if ((buttons[mainSensor].state == IDLE) && (buttons[main2Sensor].state == IDLE)) { input_report_abs(input, ABS_DISTANCE, PROX_STATUS_FAR); input_sync(input); dev_info(this->pdev, "idle set and PROX_STATUS_FAR\n"); } } else { input_report_abs(input, ABS_DISTANCE, PROX_STATUS_FAR); input_sync(input); pCurrentButton->state = IDLE; } } else { dev_info(this->pdev, "Button %d still touched.\n",counter); } break; default: /* Shouldn't be here, device only allowed ACTIVE or IDLE */ break; }; } dev_dbg(this->pdev, "Leaving Irq_Process_Close_Far()\n"); } } #ifdef CONFIG_OF static int sx9311_regulator_configure(struct sx86XX *this, bool bonoff) { struct sx9311 *pDevice = NULL; struct sx9311_platform_data *pdata = NULL; int rc = 0; if (this && (pDevice = this->pDevice) && (pdata = pDevice->hw)) { if (bonoff == true) { #if defined (CONFIG_MACH_MSM8926_T8LTE) if((lge_get_boot_mode() == LGE_BOOT_MODE_CHARGERLOGO)){ pdata->vdd_regulator = regulator_get(this->pdev, "Semtech,vdd"); regulator_set_voltage(pdata->vdd_regulator, 0,\ pdata->vdd_supply_max); regulator_set_optimum_mode(pdata->vdd_regulator, 0); regulator_put(pdata->vdd_regulator); regulator_disable(pdata->vdd_regulator); pdata->svdd_regulator = regulator_get(this->pdev, "Semtech,svdd"); regulator_set_voltage(pdata->svdd_regulator, 0,\ pdata->svdd_supply_max); regulator_set_optimum_mode(pdata->svdd_regulator, 0); regulator_put(pdata->svdd_regulator); regulator_disable(pdata->svdd_regulator); return rc; } #endif pdata->vdd_regulator = regulator_get(this->pdev, "Semtech,vdd"); if (IS_ERR(pdata->vdd_regulator)) { rc = PTR_ERR(pdata->vdd_regulator); dev_err(this->pdev, "Lookup and obtain a reference to a vdd_regulator. Fail![%d]\n", rc); return rc; } if (regulator_count_voltages(pdata->vdd_regulator) > 0) { rc = regulator_set_voltage(pdata->vdd_regulator, pdata->vdd_supply_min, pdata->vdd_supply_max); if (rc < 0) { dev_err(this->pdev, "Set vdd_regulator output voltage. Fail![%d]\n", rc); regulator_put(pdata->vdd_regulator); return rc; } rc = regulator_set_optimum_mode(pdata->vdd_regulator, pdata->vdd_load_ua); if (rc < 0) { dev_err(this->pdev, "Set vdd_regulator optimum operating mode. Fail![%d]\n", rc); regulator_put(pdata->vdd_regulator); return rc; } rc = regulator_enable(pdata->vdd_regulator); if (rc) { dev_err(this->pdev, "Enable vdd_regulator output. Fail![%d]\n", rc); regulator_set_optimum_mode(pdata->vdd_regulator, 0); regulator_put(pdata->vdd_regulator); return rc; } } pdata->svdd_regulator = regulator_get(this->pdev, "Semtech,svdd"); if (IS_ERR(pdata->svdd_regulator)) { rc = PTR_ERR(pdata->svdd_regulator); dev_err(this->pdev, "Lookup and obtain a reference to a svdd regulator, Fail![%d]\n", rc); return rc; } if (regulator_count_voltages(pdata->svdd_regulator) > 0) { rc = regulator_set_voltage(pdata->svdd_regulator, pdata->svdd_supply_min, pdata->svdd_supply_max); if (rc < 0) { dev_err(this->pdev, "Set svdd regulator output voltage, Fail![%d]\n", rc); regulator_put(pdata->svdd_regulator); return rc; } rc = regulator_set_optimum_mode(pdata->svdd_regulator, pdata->vdd_load_ua); if (rc < 0) { dev_err(this->pdev, "Set svdd_regulator optimum operating mode. Fail![%d]\n", rc); regulator_put(pdata->svdd_regulator); return rc; } rc = regulator_enable(pdata->svdd_regulator); if (rc) { dev_err(this->pdev, "Enable svdd_regulator output. Fail![%d]\n", rc); regulator_set_optimum_mode(pdata->svdd_regulator, 0); regulator_put(pdata->svdd_regulator); return rc; } } } else { if (regulator_is_enabled(pdata->vdd_regulator) > 0) { regulator_set_voltage(pdata->vdd_regulator, 0, pdata->vdd_supply_max); regulator_set_optimum_mode(pdata->vdd_regulator, 0); regulator_put(pdata->vdd_regulator); regulator_disable(pdata->vdd_regulator); } if (regulator_is_enabled(pdata->svdd_regulator) > 0) { regulator_set_voltage(pdata->svdd_regulator, 0, pdata->svdd_supply_max); regulator_set_optimum_mode(pdata->svdd_regulator, 0); regulator_put(pdata->svdd_regulator); regulator_disable(pdata->svdd_regulator); } } } return rc; } static int sx9311_init_platform_hw(struct i2c_client *client) { struct sx86XX *this = i2c_get_clientdata(client); struct sx9311 *pDevice = NULL; struct sx9311_platform_data *pdata = NULL; int rc; if (this && (pDevice = this->pDevice) && (pdata = pDevice->hw)) { sx9311_regulator_configure(this, true); if (gpio_is_valid(pdata->irq_gpio)) { rc = gpio_request(pdata->irq_gpio, "sx9311_irq_gpio"); if (rc) { dev_err(this->pdev, "Request gpio. Fail![%d]\n", rc); return rc; } rc = gpio_direction_input(pdata->irq_gpio); if (rc) { dev_err(this->pdev, "Set gpio direction. Fail![%d]\n", rc); return rc; } this->irq = client->irq = gpio_to_irq(pdata->irq_gpio); } else { dev_err(this->pdev, "Invalid irq gpio num.(init)\n"); } } return rc; } static void sx9311_exit_platform_hw(struct i2c_client *client) { struct sx86XX *this = i2c_get_clientdata(client); struct sx9311 *pDevice = NULL; struct sx9311_platform_data *pdata = NULL; if (this && (pDevice = this->pDevice) && (pdata = pDevice->hw)) { sx9311_regulator_configure(this, false); if (gpio_is_valid(pdata->irq_gpio)) { gpio_free(pdata->irq_gpio); } else { dev_err(this->pdev, "Invalid irq gpio num.(exit)\n"); } } return; } static int parse_devicetree(struct device *dev, struct sx9311_platform_data *pdata) { struct device_node *np = dev->of_node; int ret = 0; int i = 0; u32 temp_u32; u32 temp_array_u32[2]; struct sensor_dt_to_platformdata *pdtentry = NULL; struct sensor_dt_to_platformdata ar_dt_entry_data[] = { {"Semtech,irq-gpio", &pdata->irq_gpio, DT_GPIO}, {"Semtech,vdd_supply_min", &pdata->vdd_supply_min, DT_U32}, {"Semtech,vdd_supply_max", &pdata->vdd_supply_max, DT_U32}, {"Semtech,vdd_load_ua", &pdata->vdd_load_ua, DT_U32}, {"Semtech,svdd_supply_min", &pdata->svdd_supply_min, DT_U32}, {"Semtech,svdd_supply_max", &pdata->svdd_supply_max, DT_U32}, {"Semtech,svdd_load_ua", &pdata->svdd_load_ua, DT_U32}, {"Semtech,RegIrqMask", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegProxCtrl0", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegProxCtrl1", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegProxCtrl2", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegProxCtrl3", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegProxCtrl4", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegProxCtrl5", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegProxCtrl6", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegProxCtrl7", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegProxCtrl8", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegProxCtrl8", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegProxCtrl9", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegProxCtrl10", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegProxCtrl11", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegProxCtrl12", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegProxCtrl13", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegProxCtrl14", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegProxCtrl15", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegProxCtrl16", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegProxCtrl17", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegProxCtrl18", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegProxCtrl19", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegSarCtrl0", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegSarCtrl1", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegSarCtrl2", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,RegSensorSel", &temp_array_u32, DT_U8_ARRAY}, {"Semtech,InputPinsNum", &pdata->input_pins_num, DT_U32}, {"Semtech,InputMainSensor", &pdata->input_mainsensor, DT_U8}, {"Semtech,InputMainSensor2", &pdata->input_main2sensor, DT_U8}, {"Semtech,InputRefSensor", &pdata->input_refsensor, DT_U8}, {"Semtech,DynamicThres_Offset", &pdata->pStartupCheckParameters->dynamicthreshold_offset, DT_U32}, {"Semtech,DynamicThres_Temp_Slope", &pdata->pStartupCheckParameters->dynamicthreshold_temp_slope, DT_U32}, {"Semtech,DynamicThres_Hysteresis", &pdata->pStartupCheckParameters->dynamicthreshold_hysteresis, DT_U32}, {"Semtech,Calibration_Margin", &pdata->pStartupCheckParameters->calibration_margin, DT_U32}, {"Semtech,Startup_Touch_RegAvgThres", &pdata->pStartupCheckParameters->startup_touch_regavgthresh, DT_U8}, {"Semtech,Startup_Release_RegAvgThres", &pdata->pStartupCheckParameters->startup_release_regavgthresh, DT_U8}, {NULL, NULL, 0}, }; for (pdtentry = ar_dt_entry_data; pdtentry->dt_name ; ++pdtentry) { switch (pdtentry->type) { case DT_GPIO: ret = of_get_named_gpio(np, pdtentry->dt_name, 0); if (ret >= 0) { *((int *) pdtentry->ptr_data) = ret; ret = 0; dev_dbg(dev, "[%s] is [%d]. ret=%d\n", pdtentry->dt_name, *((int *)pdtentry->ptr_data), ret); } break; case DT_U32: ret = of_property_read_u32(np, pdtentry->dt_name, (u32 *) pdtentry->ptr_data); if (ret == 0) { dev_dbg(dev, "[%s] is [%d]. ret=%d\n", pdtentry->dt_name, *((int *)pdtentry->ptr_data), ret); } break; case DT_U8_ARRAY: temp_array_u32[0] = 0; temp_array_u32[1] = 0; ret = of_property_read_u32_array(np, pdtentry->dt_name, (u32 *) pdtentry->ptr_data, 2); if (ret == 0) { pdata->pi2c_reg[i].reg = (unsigned char) temp_array_u32[0]; pdata->pi2c_reg[i].val = (unsigned char) temp_array_u32[1]; pdata->i2c_reg_num = i; dev_dbg(dev, "[%s] are [0x%02x], [0x%02x]. ret=%d\n", pdtentry->dt_name, pdata->pi2c_reg[i].reg, pdata->pi2c_reg[i].val, ret); i++; } break; case DT_U8: temp_u32 = 0; ret = of_property_read_u32(np, pdtentry->dt_name, (u32 *) &temp_u32); if (ret == 0) { *((u8 *) pdtentry->ptr_data) = (u8) temp_u32; dev_dbg(dev, "[%s] is [0x%02x]. ret=%d\n", pdtentry->dt_name, *((u8 *)pdtentry->ptr_data), ret); } break; default: dev_err(dev, "%d is an unknown DT entry type. Fail!\n", pdtentry->type); ret = -EBADE; break; } if (ret) { dev_err(dev, "Check '%s' DT entry. Fail!\n", pdtentry->dt_name); return ret; } } return 0; } #endif /* get the NIRQ state (1->NIRQ-low, 0->NIRQ-high) */ static int sx9311_get_nirq_state(void) { return !gpio_get_value(GPIO_SX9311_NIRQ); } #ifdef USE_COMMON_SYSFS static ssize_t cap_store_onoffsensor(struct sx86XX *this, const char *buf, size_t count) { unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; dev_info(this->pdev,"request onoff val = %d\n", (int) val); if (val == ON_SENSOR) onoff_sensor(this, ENABLE_IRQ_MASK | ENABLE_SENSOR_PINS); else if (val == OFF_SENSOR) onoff_sensor(this, DISABLE_IRQ_MASK | DISABLE_SENSOR_PINS); return count; } static ssize_t cap_store_docalibration(struct sx86XX *this, const char *buf, size_t count) { struct sx9311 *pDevice = NULL; unsigned char cal_scanperiod = SCANPERIOD_CAL;// Set SCANPERIOD[6:4] - 000(30ms). unsigned char write_RegProxCtrl0 = 0x00; unsigned char mainSensor = 0; unsigned char main2Sensor = 0; unsigned char refSensor = 0; struct smtc_cal_data capMain_cal_data[COLLECT_NUM]; struct smtc_cal_data capMain2_cal_data[COLLECT_NUM]; struct smtc_cal_data capRef_cal_data[COLLECT_NUM]; s32 avg_Capacitance_Main = 0; s32 avg_Useful_Main = 0; s32 avg_Offset_Main = 0; s32 avg_Capacitance_Main2 = 0; s32 avg_Useful_Main2 = 0; s32 avg_Offset_Main2 = 0; s32 avg_Capacitance_Ref = 0; s32 avg_Useful_Ref = 0; s32 avg_Offset_Ref = 0; s32 avg_Capacitance_Ref_dynamicthreshold = 0; s32 nhysteresis = 0; s32 capMargin = 0; s32 capMargin2 = 0; bool is_different_offset = false; bool is_over_gap_useful = false; bool is_over_useful = false; int ret = 0; if (this && (pDevice = this->pDevice) && !running_cal_or_reset) { int i = 0; u8 old_RegIrqMsk_val = 0; u8 old_RegCtrl0_val = 0; unsigned char conv_mainSensor = 0; unsigned char conv_main2Sensor = 0; unsigned char conv_refSensor = 0; running_cal_or_reset = true; dev_info(this->pdev, "calibration start!!!\n"); mainSensor = (unsigned char)pDevice->hw->input_mainsensor; if (valid_multiple_input_pins(this)) main2Sensor = (unsigned char)pDevice->hw->input_main2sensor; refSensor = (unsigned char)pDevice->hw->input_refsensor; conv_mainSensor = conv_sensorsel_to_sensoren(mainSensor); if (valid_multiple_input_pins(this)) conv_main2Sensor = conv_sensorsel_to_sensoren(main2Sensor); conv_refSensor = conv_sensorsel_to_sensoren(refSensor); write_RegProxCtrl0 = (unsigned char) ((cal_scanperiod << 4) | (conv_mainSensor | conv_main2Sensor | conv_refSensor)); // Backup RegIrqMask & RegProxCtrl0 value. // And, Change RegIrqMask & RegProxCtrl0(scanperiod) value for calibration. read_register(this, SX9311_IRQ_ENABLE_REG, &old_RegIrqMsk_val); read_register(this, SX9311_CPS_CTRL0_REG, &old_RegCtrl0_val); write_register(this, SX9311_IRQ_ENABLE_REG, 0x70); write_register(this, SX9311_CPS_CTRL0_REG, write_RegProxCtrl0); msleep(100); /* make sure everything is running */ manual_offset_calibration(this); // This should cover most of the scan periods, if extremely large may // want to set this to 500 msleep(500); /* make sure manual offset has been fully done */ // Clear flags because sensor is calibrationing. this->inStartupTouch = false; check_allnear = false; // Calculate out the Cap information for Main/(Main2/)Ref Pins. for (i = 0; i < COLLECT_NUM; i++) { calculate_CSx_rawdata(this, mainSensor, &capMain_cal_data[i].Useful_CSx, &capMain_cal_data[i].Offset_CSx, &capMain_cal_data[i].Calculate_CSx); if (valid_multiple_input_pins(this)) { calculate_CSx_rawdata(this, main2Sensor, &capMain2_cal_data[i].Useful_CSx, &capMain2_cal_data[i].Offset_CSx, &capMain2_cal_data[i].Calculate_CSx); } calculate_CSx_rawdata(this, refSensor, &capRef_cal_data[i].Useful_CSx, &capRef_cal_data[i].Offset_CSx, &capRef_cal_data[i].Calculate_CSx); msleep(50); } // To sort the collected value. sort((void *) &capMain_cal_data, COLLECT_NUM, sizeof(struct smtc_cal_data), (compfn) cmp_rawdata, NULL); if (valid_multiple_input_pins(this)) { sort((void *) &capMain2_cal_data, COLLECT_NUM, sizeof(struct smtc_cal_data), (compfn) cmp_rawdata, NULL); } sort((void *) &capRef_cal_data, COLLECT_NUM, sizeof(struct smtc_cal_data), (compfn) cmp_rawdata, NULL); // Check readback sensor raw data. // 1. Check Offset value.(is equal values?) // 2. Check Useful value.(is over min/max gap? is over init range?) for (i = 0; i < COLLECT_NUM; i++) { if (capMain_cal_data[i].Offset_CSx != capMain_cal_data[COLLECT_NUM/2].Offset_CSx) { is_different_offset = true; dev_info(this->pdev, "Calibration Fail! different(offset)! [%d] %d\n", i, capMain_cal_data[i].Offset_CSx); } } if (is_different_offset == false) { if ((capMain_cal_data[COLLECT_NUM-1].Useful_CSx - capMain_cal_data[0].Useful_CSx) > 2000) { is_over_gap_useful = true; dev_info(this->pdev, "Calibration Fail! over gap(useful)! [gap = %d(%d - %d)]\n", ((capMain_cal_data[COLLECT_NUM-1].Useful_CSx) - (capMain_cal_data[0].Useful_CSx)), capMain_cal_data[COLLECT_NUM-1].Useful_CSx, capMain_cal_data[0].Useful_CSx); } for (i = 0; i < COLLECT_NUM; i++) { if ((capMain_cal_data[i].Useful_CSx < -8000) || (capMain_cal_data[i].Useful_CSx > 8000)) { is_over_useful = true; dev_info(this->pdev, "Calibration Fail! over range(useful)! [%d] %d\n", i, capMain_cal_data[i].Useful_CSx); } } } if (is_different_offset || is_over_gap_useful || is_over_useful) { ret = write_calibration_data(this, 0, 0, 0, false); //if (valid_multiple_input_pins(this)) // ret = write_calibration_data(this, 0, 0, 0, true); running_cal_or_reset = false; return count; } // Calculate the average capacitance value about the Main/(Main2/)Ref Pins. // 2 max & 2 min values are excluded. for (i = FILTER_NUM; i < COLLECT_NUM - FILTER_NUM; i++) { avg_Capacitance_Main += capMain_cal_data[i].Calculate_CSx; avg_Useful_Main += capMain_cal_data[i].Useful_CSx; avg_Offset_Main += capMain_cal_data[i].Offset_CSx; } avg_Capacitance_Main = avg_Capacitance_Main / (COLLECT_NUM - (FILTER_NUM * 2)); avg_Useful_Main = avg_Useful_Main / (COLLECT_NUM - (FILTER_NUM * 2)); avg_Offset_Main = avg_Offset_Main / (COLLECT_NUM - (FILTER_NUM * 2)); dev_info(this->pdev, "avg_Capacitance_Main = %d, avg_Useful_Main = %d, avg_Offset_Main = %d\n", avg_Capacitance_Main, avg_Useful_Main, avg_Offset_Main); if (valid_multiple_input_pins(this)) { for (i = FILTER_NUM; i < COLLECT_NUM - FILTER_NUM; i++) { avg_Capacitance_Main2 += capMain2_cal_data[i].Calculate_CSx; avg_Useful_Main2 += capMain2_cal_data[i].Useful_CSx; avg_Offset_Main2 += capMain2_cal_data[i].Offset_CSx; } avg_Capacitance_Main2 = avg_Capacitance_Main2 / (COLLECT_NUM - (FILTER_NUM * 2)); avg_Useful_Main2 = avg_Useful_Main2 / (COLLECT_NUM - (FILTER_NUM * 2)); avg_Offset_Main2 = avg_Offset_Main2 / (COLLECT_NUM - (FILTER_NUM * 2)); dev_info(this->pdev, "avg_Capacitance_Main2 = %d, avg_Useful_Main2 = %d, avg_Offset_Main2 = %d\n", avg_Capacitance_Main2, avg_Useful_Main2, avg_Offset_Main2); } for (i = FILTER_NUM; i < COLLECT_NUM - FILTER_NUM; i++) { avg_Capacitance_Ref += capRef_cal_data[i].Calculate_CSx; avg_Useful_Ref += capRef_cal_data[i].Useful_CSx; avg_Offset_Ref += capRef_cal_data[i].Offset_CSx; } avg_Capacitance_Ref = avg_Capacitance_Ref / (COLLECT_NUM - (FILTER_NUM * 2)); avg_Useful_Ref = avg_Useful_Ref / (COLLECT_NUM - (FILTER_NUM * 2)); avg_Offset_Ref = avg_Offset_Ref / (COLLECT_NUM - (FILTER_NUM * 2)); dev_info(this->pdev, "avg_Capacitance_Ref = %d, avg_Useful_Ref = %d, avg_Offset_Ref = %d\n", avg_Capacitance_Ref, avg_Useful_Ref, avg_Offset_Ref); // Calculate the dynamic thershold through the ref sensor. avg_Capacitance_Ref_dynamicthreshold = pDevice->pStartupCheckParameters->dynamicthreshold_offset + ((pDevice->pStartupCheckParameters->dynamicthreshold_temp_slope * avg_Capacitance_Ref) / 10); // Calculate capacitance margin value. // And, Save margin & offset values. nhysteresis = pDevice->pStartupCheckParameters->dynamicthreshold_hysteresis; capMargin = avg_Capacitance_Main - avg_Capacitance_Ref_dynamicthreshold + nhysteresis; ret = write_calibration_data(this, capMargin, capMain_cal_data[COLLECT_NUM/2].Offset_CSx, avg_Capacitance_Main, false); if (valid_multiple_input_pins(this)) { capMargin2 = avg_Capacitance_Main2 - avg_Capacitance_Ref_dynamicthreshold + nhysteresis; ret = write_calibration_data(this, capMargin2, capMain2_cal_data[COLLECT_NUM/2].Offset_CSx, avg_Capacitance_Main2, true); } write_calibration_backup_data(this, avg_Capacitance_Main, (s16) avg_Useful_Main, (u16) avg_Offset_Main); if (valid_multiple_input_pins(this)) { write_calibration_backup_data(this, avg_Capacitance_Main2, (s16)avg_Useful_Main2, (u16) avg_Offset_Main2); } write_calibration_backup_data(this, avg_Capacitance_Ref, (s16) avg_Useful_Ref, (u16) avg_Offset_Ref); // Restore RegIrqMask & RegProxCtrl0(scanperiod) value. write_register(this, SX9311_IRQ_ENABLE_REG, old_RegIrqMsk_val); write_register(this, SX9311_CPS_CTRL0_REG, old_RegCtrl0_val); // Must be sure to set the Main CS pin. write_register(this, SX9311_SENSORSEL_REG, mainSensor); dev_info(this->pdev, "calibration end!!!\n"); running_cal_or_reset = false; } return count; } static ssize_t cap_store_checkallnear(struct sx86XX *this, const char *buf, size_t count) { unsigned long val; if (strict_strtoul(buf, 0, &val)) return -EINVAL; dev_info(this->pdev,"checkallnear set val = %d\n", (int) val); if (val == 0) check_allnear = false; else if (val == 1) check_allnear = true; return count; } static ssize_t cap_show_count_inputpins(struct sx86XX *this, char *buf) { int count_inputpins = 0; struct sx9311 *pDevice = NULL; struct sx9311_platform_data *pdata = NULL; if (this && (pDevice = this->pDevice) && (pdata = pDevice->hw)) { count_inputpins = pdata->input_pins_num; if (count_inputpins > 1) { if (valid_multiple_input_pins(this) == false) count_inputpins = 1; } } dev_info(this->pdev,"count input pins = %d\n", count_inputpins); return sprintf(buf, "%d\n", count_inputpins); } static ssize_t cap_show_proxstatus(struct sx86XX *this, char *buf) { struct sx9311 *pDevice = NULL; struct _buttoninfo *buttons = NULL; u8 mainSensor, main2Sensor; int prox_status = -1; if (this && (pDevice = this->pDevice)) { buttons = pDevice->pButtonInformation->buttons; mainSensor = pDevice->hw->input_mainsensor; if (valid_multiple_input_pins(this)) { main2Sensor = pDevice->hw->input_main2sensor; if (check_allnear) { if ((buttons[mainSensor].state == IDLE) || (buttons[main2Sensor].state == IDLE)) prox_status = IDLE; if ((buttons[mainSensor].state == ACTIVE) && (buttons[main2Sensor].state == ACTIVE)) prox_status = ACTIVE; } else { if ((buttons[mainSensor].state == IDLE) && (buttons[main2Sensor].state == IDLE)) prox_status = IDLE; if ((buttons[mainSensor].state == ACTIVE) || (buttons[main2Sensor].state == ACTIVE)) prox_status = ACTIVE; } } else { prox_status = buttons[mainSensor].state; } } return sprintf(buf, "%d\n", prox_status); } static ssize_t cap_show_regproxdata(struct sx86XX *this, char *buf) { s16 main_Useful = 0, main_Avg = 0, main_Diff = 0; u16 main_Offset = 0; s16 main2_Useful = 0, main2_Avg = 0, main2_Diff = 0; u16 main2_Offset = 0; s16 ref_Useful = 0, ref_Avg = 0, ref_Diff = 0; u16 ref_Offset = 0; u8 mainSensor, main2Sensor, refSensor; int current_xo_therm = 0; char buf_bstate_main[5] = ""; char buf_bstate_main2[5] = ""; char buf_line[64] = ""; char buf_regproxdata[256] = ""; int nlength = 0; struct sx9311 *pDevice = NULL; struct _buttoninfo *buttons = NULL; memset(buf_bstate_main, 0, sizeof(buf_bstate_main)); memset(buf_bstate_main2, 0, sizeof(buf_bstate_main2)); memset(buf_line, 0, sizeof(buf_line)); memset(buf_regproxdata, 0, sizeof(buf_regproxdata)); if (this && (pDevice = this->pDevice) && !running_cal_or_reset) { buttons = pDevice->pButtonInformation->buttons; // Select Main Sensor, Readback Reg Sensor Data mainSensor = pDevice->hw->input_mainsensor; read_sensor_regdata(this, mainSensor, &main_Useful, &main_Avg, &main_Diff, &main_Offset); (buttons[mainSensor].state) ? strcpy(buf_bstate_main, "F"):strcpy(buf_bstate_main, "N"); dev_info(this->pdev,"capMain = %6d %6d %6d %6d %s\n", main_Useful, main_Avg, main_Diff, main_Offset, buf_bstate_main); // Select Main2 Sensor, Readback Reg Sensor Data if (valid_multiple_input_pins(this)) { main2Sensor = pDevice->hw->input_main2sensor; read_sensor_regdata(this, main2Sensor, &main2_Useful, &main2_Avg, &main2_Diff, &main2_Offset); (buttons[main2Sensor].state) ? strcpy(buf_bstate_main2, "F"):strcpy(buf_bstate_main2, "N"); dev_info(this->pdev,"capMain2 = %6d %6d %6d %6d %s\n", main2_Useful, main2_Avg, main2_Diff, main2_Offset, buf_bstate_main2); } // Select Reference Sensor, Readback Reg Sensor Data refSensor = pDevice->hw->input_refsensor; read_sensor_regdata(this, refSensor, &ref_Useful, &ref_Avg, &ref_Diff, &ref_Offset); dev_info(this->pdev,"capRef = %6d %6d %6d %6d\n", ref_Useful, ref_Avg, ref_Diff, ref_Offset); // Please Select Main Sensor again. write_register(this, SX9311_SENSORSEL_REG, mainSensor); read_xo_therm_data(this, &current_xo_therm); } sprintf(buf_line, "[M]%6d %6d %6d %6d %s %3d\n", main_Useful, main_Avg, main_Diff, main_Offset, buf_bstate_main, current_xo_therm); strcpy(buf_regproxdata, buf_line); if (this && valid_multiple_input_pins(this)) { sprintf(buf_line, "[S]%6d %6d %6d %6d %s\n", main2_Useful, main2_Avg, main2_Diff, main2_Offset, buf_bstate_main2); nlength = strlen(buf_regproxdata); strcpy(&buf_regproxdata[nlength], buf_line); } sprintf(buf_line, "[R]%6d %6d %6d %6d\n", ref_Useful, ref_Avg, ref_Diff, ref_Offset); nlength = strlen(buf_regproxdata); strcpy(&buf_regproxdata[nlength], buf_line); return sprintf(buf, "%s", buf_regproxdata); } static ssize_t cap_store_regreset(struct sx86XX *this, const char *buf, size_t count) { struct sx9311 *pDevice = NULL; struct input_dev *input = NULL; unsigned long val; int i = 0; if (strict_strtoul(buf, 0, &val)) return -EINVAL; if (this && (pDevice = this->pDevice) && !running_cal_or_reset) { running_cal_or_reset = true; if (val == SX9311_SOFTRESET) { dev_info(this->pdev, "reset start!!!\n"); for (i = 0; i < pDevice->pButtonInformation->buttonSize; i++) { pDevice->pButtonInformation->buttons[i].state = IDLE; } input = pDevice->pButtonInformation->input; input_report_abs(input, ABS_DISTANCE, PROX_STATUS_FAR); input_sync(input); //sx86XX_suspend(this); //sx86XX_resume(this); //disable_irq(this->irq); #ifdef USE_THREADED_IRQ mutex_lock(&this->mutex); /* Just in case need to reset any uncaught interrupts */ sx86XX_process_interrupt(this,0); mutex_unlock(&this->mutex); #else sx86XX_schedule_work(this,0); #endif initialize_device(this); //enable_irq(this->irq); dev_info(this->pdev, "reset end!!!\n"); } running_cal_or_reset = false; } return count; } static ssize_t cap_show_regproxctrl0(struct sx86XX *this, char *buf) { u8 reg_value = 0; read_register(this, SX9311_CPS_CTRL0_REG, &reg_value); return sprintf(buf, "0x%02x\n", reg_value); } static ssize_t cap_store_regproxctrl0(struct sx86XX *this, const char *buf, size_t count) { struct sx9311 *pDevice = NULL; struct input_dev *input = NULL; unsigned long val; unsigned long val_check; int i = 0; int ret = 0; if (strict_strtoul(buf, 0, &val)) return -EINVAL; ret = write_register(this, SX9311_CPS_CTRL0_REG, val); if (ret > 0) { val_check = val & SENSOREN_CS2; if (val_check == SENSOREN_DISABLE_ALL) { /* Initialize prox status : default FAR */ if (this && (pDevice = this->pDevice)) { for (i = 0; i < pDevice->pButtonInformation->buttonSize; i++) { pDevice->pButtonInformation->buttons[i].state = IDLE; } input = pDevice->pButtonInformation->input; input_report_abs(input, ABS_DISTANCE, PROX_STATUS_FAR); input_sync(input); } } } return count; } #define LGE_CAP_NAME "lge_cap" static struct sys_device lge_cap_sys_device; struct lge_cap_attribute { struct attribute attr; ssize_t (*show)(struct sx86XX *this, char *buf); ssize_t (*store)(struct sx86XX *this, const char *buf, size_t count); }; #define LGE_CAP_ATTR(_name, _mode, _show, _store) \ struct lge_cap_attribute lge_cap_attr_##_name = __ATTR(_name, _mode, _show, _store) static LGE_CAP_ATTR(onoff, 0664, NULL, cap_store_onoffsensor); static LGE_CAP_ATTR(docalibration,0664, NULL, cap_store_docalibration); static LGE_CAP_ATTR(checkallnear, 0664, NULL, cap_store_checkallnear); static LGE_CAP_ATTR(cntinputpins, 0664, cap_show_count_inputpins, NULL); static LGE_CAP_ATTR(proxstatus, 0664, cap_show_proxstatus, NULL); static LGE_CAP_ATTR(regproxdata, 0664, cap_show_regproxdata, NULL); static LGE_CAP_ATTR(regreset, 0664, NULL, cap_store_regreset); static LGE_CAP_ATTR(regproxctrl0, 0664, cap_show_regproxctrl0, cap_store_regproxctrl0); static struct attribute *lge_cap_attribute_list[] = { &lge_cap_attr_onoff.attr, &lge_cap_attr_docalibration.attr, &lge_cap_attr_checkallnear.attr, &lge_cap_attr_cntinputpins.attr, &lge_cap_attr_proxstatus.attr, &lge_cap_attr_regproxdata.attr, &lge_cap_attr_regreset.attr, &lge_cap_attr_regproxctrl0.attr, NULL, }; static ssize_t lge_cap_attr_show(struct kobject *lge_cap_kobj, struct attribute *attr, char *buf) { struct sx86XX *this = container_of(lge_cap_kobj, struct sx86XX, lge_cap_kobj); struct lge_cap_attribute *lge_cap_priv = container_of(attr, struct lge_cap_attribute, attr); ssize_t ret = 0; if (lge_cap_priv->show) ret = lge_cap_priv->show(this, buf); return ret; } static ssize_t lge_cap_attr_store(struct kobject *lge_cap_kobj, struct attribute *attr, const char *buf, size_t count) { struct sx86XX *this = container_of(lge_cap_kobj, struct sx86XX, lge_cap_kobj); struct lge_cap_attribute *lge_cap_priv = container_of(attr, struct lge_cap_attribute, attr); ssize_t ret = 0; if (lge_cap_priv->store) ret = lge_cap_priv->store(this, buf, count); return ret; } static const struct sysfs_ops lge_cap_sysfs_ops = { .show = lge_cap_attr_show, .store = lge_cap_attr_store, }; static struct kobj_type lge_cap_kobj_type = { .sysfs_ops = &lge_cap_sysfs_ops, .default_attrs = lge_cap_attribute_list, }; static struct sysdev_class lge_cap_sys_class = { .name = LGE_CAP_NAME, }; static struct sys_device lge_cap_sys_device = { .id = 0, .cls = &lge_cap_sys_class, }; #endif /*! \fn static int sx9311_probe(struct i2c_client *client, const struct i2c_device_id *id) * \brief Probe function * \param client pointer to i2c_client * \param id pointer to i2c_device_id * \return Whether probe was successful */ static int sx9311_probe(struct i2c_client *client, const struct i2c_device_id *id) { int i = 0; int err = 0; struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent); struct sx86XX *this = NULL; struct sx9311 *pDevice = NULL; struct sx9311_platform_data *pplatData = NULL; struct _totalbuttoninformation *pButtonInformationData = NULL; struct _startupcheckparameters *pStartupCheckParameters = NULL; struct input_dev *input = NULL; dev_info(&client->dev, "sx9311_probe()\n"); if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_READ_WORD_DATA)) { dev_err(&client->dev, "Check i2c functionality.Fail!\n"); err = -EIO; goto exit; } pButtonInformationData = devm_kzalloc(&client->dev, sizeof(struct _totalbuttoninformation), GFP_KERNEL); if (!pButtonInformationData) { dev_err(&client->dev, "Failed to allocate memory(_totalButtonInformation)\n"); err = -ENOMEM; goto exit; } pButtonInformationData->buttons = psmtcButtons; pButtonInformationData->buttonSize = ARRAY_SIZE(psmtcButtons), pStartupCheckParameters = devm_kzalloc(&client->dev, sizeof(struct _startupcheckparameters), GFP_KERNEL); if (!pStartupCheckParameters) { dev_err(&client->dev, "Failed to allocate memory(_startupCheckParameters)\n"); err = -ENOMEM; goto exit; } //pStartupCheckParameters = &smtcTouchCheckParameters; pplatData = devm_kzalloc(&client->dev, sizeof(struct sx9311_platform_data), GFP_KERNEL); if (!pplatData) { dev_err(&client->dev, "Failed to allocate memory(sx9311_platform_data)\n"); err = -ENOMEM; goto exit; } pplatData->pButtonInformation = pButtonInformationData; pplatData->pStartupCheckParameters = pStartupCheckParameters; pplatData->get_is_nirq_low = sx9311_get_nirq_state; pplatData->init_platform_hw = NULL; pplatData->exit_platform_hw = NULL; client->dev.platform_data = pplatData; #ifdef CONFIG_OF if (client->dev.of_node) { unsigned char val_regproxctrl1 = 0; unsigned char val_regproxctrl2 = 0; err = parse_devicetree(&client->dev, pplatData); if (err) { dev_err(&client->dev, "Failed to parse device tree.[%d]\n", err); goto exit; } while (i < pplatData->i2c_reg_num) { if (pplatData->pi2c_reg[i].reg == SX9311_CPS_CTRL1_REG) val_regproxctrl1 = pplatData->pi2c_reg[i].val; else if (pplatData->pi2c_reg[i].reg == SX9311_CPS_CTRL2_REG) val_regproxctrl2 = pplatData->pi2c_reg[i].val; i++; } pplatData->capacitance_range = conv_regval_to_range(val_regproxctrl1); pplatData->gain_factor = conv_regval_to_gain(val_regproxctrl2); /* set functions of platform data */ pplatData->init_platform_hw = sx9311_init_platform_hw; pplatData->exit_platform_hw = sx9311_exit_platform_hw; } #endif /* create memory for main struct */ this = devm_kzalloc(&client->dev, sizeof(struct sx86XX), GFP_KERNEL); if (!this) { dev_err(&client->dev, "Failed to allocate memory(sx86XX)\n"); err = -ENOMEM; goto exit; } if (this) { /* In case we need to reinitialize data * (e.q. if suspend reset device) */ this->init = initialize_device; /* shortcut to read status of interrupt */ this->refreshStatus = read_regIrqStat; /* pointer to function from platform data to get pendown * (1->NIRQ=0, 0->NIRQ=1) */ this->get_nirq_low = pplatData->get_is_nirq_low; /* save irq in case we need to reference it */ this->irq = client->irq; /* do we need to create an irq timer after interrupt ? */ this->useIrqTimer = 0; /* Setup function to call on corresponding reg irq source bit */ if (MAX_NUM_STATUS_BITS >= 8) { this->statusFunc[0] = 0; /* TXEN_STAT */ this->statusFunc[1] = 0; /* UNUSED */ this->statusFunc[2] = 0; /* UNUSED */ this->statusFunc[3] = 0; /* CONVERSION_IRQ(CONV_STAT) */ this->statusFunc[4] = Irq_Process_Close_Far; /* COMPENSATION_IRQ(COMP_STAT) */ this->statusFunc[5] = Irq_Process_Close_Far; /* FAR_IRQ(RELEASE_STAT) */ this->statusFunc[6] = Irq_Process_Close_Far; /* CLOSE_IRQ(TOUCH_STAT) */ this->statusFunc[7] = 0; /* RESET_STAT */ } /* setup i2c communication */ this->bus = client; i2c_set_clientdata(client, this); /* record device struct */ this->pdev = &client->dev; /* create memory for device specific struct */ pDevice = devm_kzalloc(&client->dev, sizeof(struct sx9311), GFP_KERNEL); if (!pDevice) { dev_err(&client->dev, "Failed to allocate memory(sx9311)\n"); err = -ENOMEM; goto exit; } this->pDevice = pDevice; if (pDevice) { /* Add Pointer to main platform data struct */ pDevice->hw = pplatData; /* Initialize the button information initialized with keycodes */ pDevice->pButtonInformation = pplatData->pButtonInformation; /* Initialize the startup parameters */ pDevice->pStartupCheckParameters = pplatData->pStartupCheckParameters; /* Check if we hava a platform initialization function to call*/ if (pplatData->init_platform_hw) pplatData->init_platform_hw(client); /* Create the input device */ input = input_allocate_device(); if (!input) { return -ENOMEM; } /* Set all the keycodes */ /*__set_bit(EV_KEY, input->evbit);*/ __set_bit(EV_ABS, input->evbit); input_set_abs_params(input, ABS_DISTANCE, 0, 1, 0, 0); for (i = 0; i < pDevice->pButtonInformation->buttonSize; i++) { /*__set_bit(pDevice->pButtonInformation->buttons[i].keycode, input->keybit);*/ pDevice->pButtonInformation->buttons[i].state = IDLE; } /* save the input pointer and finish initialization */ pDevice->pButtonInformation->input = input; input->name = "SX9311 Cap Touch"; input->id.bustype = BUS_I2C; //input->id.product = sx863x->product; //input->id.version = sx863x->version; if(input_register_device(input)) return -ENOMEM; /* for accessing items in user data (e.g. calibrate) */ err = sysfs_create_group(&client->dev.kobj, &sx9311_attr_group); if (err) printk(KERN_INFO"sysfs create fail!"); #ifdef USE_COMMON_SYSFS err = sysdev_class_register(&lge_cap_sys_class); if (err < 0) { printk(KERN_INFO"lge_cap sysfs create fail!"); goto err_lge_cap_sys_class_register; } err = sysdev_register(&lge_cap_sys_device); if (err < 0) { printk(KERN_INFO"lge_cap sysdev_register is failed!"); goto err_lge_cap_sys_dev_register; } err = kobject_init_and_add(&this->lge_cap_kobj, &lge_cap_kobj_type, pDevice->pButtonInformation->input->dev.kobj.parent, "%s", LGE_CAP_NAME); if (err < 0) { printk(KERN_INFO"lge_cap kobject_init_and_add is failed"); goto err_lge_cap_sysfs_init_and_add; } #endif wake_lock_init(&this->capsensor_wake_lock, WAKE_LOCK_SUSPEND, "capsensor_wakeup"); } sx86XX_init(this); /* default sensor off */ onoff_sensor(this, DISABLE_IRQ_MASK | DISABLE_SENSOR_PINS); return 0; } return -1; #ifdef USE_COMMON_SYSFS err_lge_cap_sysfs_init_and_add: kobject_del(&this->lge_cap_kobj); err_lge_cap_sys_dev_register: sysdev_unregister(&lge_cap_sys_device); err_lge_cap_sys_class_register: sysdev_class_unregister(&lge_cap_sys_class); #endif exit: return err; } /*! \fn static int sx9311_remove(struct i2c_client *client) * \brief Called when device is to be removed * \param client Pointer to i2c_client struct * \return Value from sx86XX_remove() */ static int sx9311_remove(struct i2c_client *client) { struct sx86XX *this = i2c_get_clientdata(client); struct sx9311 *pDevice = NULL; struct sx9311_platform_data *pplatData = NULL; if (this && (pDevice = this->pDevice)) { disable_irq_wake(this->irq); input_unregister_device(pDevice->pButtonInformation->input); sysfs_remove_group(&client->dev.kobj, &sx9311_attr_group); pplatData = client->dev.platform_data; if (pplatData && pplatData->exit_platform_hw) pplatData->exit_platform_hw(client); kfree(this->pDevice); } return sx86XX_remove(this); } #ifdef CONFIG_PM /*====================================================*/ /***** Kernel Suspend *****/ static int sx9311_suspend(struct i2c_client *client, pm_message_t mesg) { struct sx86XX *this = i2c_get_clientdata(client); sx86XX_suspend(this); return 0; } /***** Kernel Resume *****/ static int sx9311_resume(struct i2c_client *client) { struct sx86XX *this = i2c_get_clientdata(client); sx86XX_resume(this); return 0; } /*====================================================*/ #else #define sx9311_suspend NULL #define sx9311_resume NULL #endif /* CONFIG_PM */ static struct i2c_device_id sx9311_id[] = { { "sx9311", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, sx9311_id); #ifdef CONFIG_OF static struct of_device_id sx9311_match_table[] = { { .compatible = "Semtech,sx9311",}, { }, }; #else #define sx9311_match_table NULL #endif static struct i2c_driver sx9311_driver = { .driver = { .owner = THIS_MODULE, .name = "sx9311", .of_match_table = sx9311_match_table, }, .id_table = sx9311_id, .probe = sx9311_probe, .remove = __devexit_p(sx9311_remove), .suspend = sx9311_suspend, .resume = sx9311_resume, }; static int __init sx9311_init(void) { printk(KERN_INFO "sx9311 driver: initialize."); return i2c_add_driver(&sx9311_driver); } static void __exit sx9311_exit(void) { printk(KERN_INFO "sx9311 driver: release."); i2c_del_driver(&sx9311_driver); } module_init(sx9311_init); module_exit(sx9311_exit); MODULE_AUTHOR("Semtech Corp. (http://www.semtech.com/)"); MODULE_DESCRIPTION("SX9311 Capacitive Touch Controller Driver"); MODULE_LICENSE("GPL"); MODULE_VERSION("0.1");
KAsp3rd/android_kernel_lge_v496
drivers/input/sensor/sx9311.c
C
gpl-2.0
107,405
<?php require_once '../lib/DataSourceResult.php'; require_once '../lib/Kendo/Autoload.php'; require_once '../include/header.php'; ?> <div class="demo-section k-rtl"> <h2>Select Continents</h2> <?php $multiselect = new \Kendo\UI\MultiSelect('select'); $multiselect->dataTextField('text') ->dataValueField('value') ->dataSource(array( array('text' => 'Africa', 'value' => '1'), array('text' => 'Europe', 'value' => '2'), array('text' => 'Asia', 'value' => '3'), array('text' => 'North America', 'value' => '4'), array('text' => 'South America', 'value' => '5'), array('text' => 'Antarctica', 'value' => '6'), array('text' => 'Australia', 'value' => '7') )); echo $multiselect->render(); ?> <style scoped> .demo-section { width: 250px; margin: 35px auto 50px; padding: 30px; } .demo-section h2 { text-transform: uppercase; font-size: 1.2em; margin-bottom: 10px; } </style> </div> <?php require_once '../include/footer.php'; ?>
kabsila/wordpress
new/wrappers/php/multiselect/right-to-left-support.php
PHP
gpl-2.0
1,197
/** ****************************************************************************** * @file USB_Host/CDC_Standalone/Src/lcd_log_conf.h * @author MCD Application Team * @version V1.1.0 * @date 26-June-2014 * @brief LCD Log configuration file. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __LCD_LOG_CONF_H #define __LCD_LOG_CONF_H /* Includes ------------------------------------------------------------------*/ #include "stm324x9i_eval_lcd.h" #include <stdio.h> /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Define the LCD default text color */ #define LCD_LOG_DEFAULT_COLOR LCD_COLOR_WHITE /* Comment the line below to disable the scroll back and forward features */ #define LCD_SCROLL_ENABLED 1 #define LCD_LOG_HEADER_FONT Font16 #define LCD_LOG_FOOTER_FONT Font12 #define LCD_LOG_TEXT_FONT Font12 /* Define the LCD LOG Color */ #define LCD_LOG_BACKGROUND_COLOR LCD_COLOR_BLACK #define LCD_LOG_TEXT_COLOR LCD_COLOR_WHITE #define LCD_LOG_SOLID_BACKGROUND_COLOR LCD_COLOR_BLUE #define LCD_LOG_SOLID_TEXT_COLOR LCD_COLOR_WHITE /* Define the cache depth */ #define CACHE_SIZE 100 #define YWINDOW_SIZE 13 #if (YWINDOW_SIZE > 14) #error "Wrong YWINDOW SIZE" #endif /* Redirect the printf to the LCD */ #ifdef __GNUC__ /* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf set to 'Yes') calls __io_putchar() */ #define LCD_LOG_PUTCHAR int __io_putchar(int ch) #else #define LCD_LOG_PUTCHAR int fputc(int ch, FILE *f) #endif /* __GNUC__ */ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ #endif /* __LCD_LOG_CONF_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
matianfu/stm32f4cube13
Projects/STM324x9I_EVAL/Applications/USB_Host/CDC_Standalone/Inc/lcd_log_conf.h
C
gpl-2.0
4,023
<?php /* Template Name: Search_results */ ?> <?php get_header(); ?> <ul class="columna primera"> <?php blogsfera_widget_my_blog(); ?> <?php blogsfera_widget_chat(); ?> <?php blogsfera_widget_most_read(); ?> <?php blogsfera_widget_news(); ?> </ul> <ul class="columna"> <?php blogsfera_widget_search_results(); ?> <?php blogsfera_widget_recent_users(); ?> <?php blogsfera_widget_recent_articles(); ?> </ul> <ul class="columna"> <?php blogsfera_widget_search(); ?> <?php blogsfera_widget_avisos(array('blog_id' => 2)); ?> <?php blogsfera_widget_tag_cloud(); ?> </ul> <?php get_footer(); ?>
alx/blogsfera
wp-content/themes/portal/search_results.php
PHP
gpl-2.0
602
# -*- coding: utf-8 -*- from flask import Flask from flask.ext.pymongo import PyMongo import config from views import diary def create_app(cfg): app = Flask(__name__) app.config.from_object(cfg) return app # Application creation. app = create_app(config) # Database configuration. db = PyMongo() # Blueprints registration. app.register_blueprint(diary) if __name__ == '__main__': app.run()
GruPy-RN/agenda_flask
diary/__init__.py
Python
gpl-2.0
416
{-| Implementation of cluster-wide logic. This module holds all pure cluster-logic; I\/O related functionality goes into the /Main/ module for the individual binaries. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. 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. -} module Ganeti.HTools.Cluster ( -- * Types AllocSolution(..) , EvacSolution(..) , Table(..) , CStats(..) , AllocNodes , AllocResult , AllocMethod , AllocSolutionList -- * Generic functions , totalResources , computeAllocationDelta -- * First phase functions , computeBadItems -- * Second phase functions , printSolutionLine , formatCmds , involvedNodes , splitJobs -- * Display functions , printNodes , printInsts -- * Balacing functions , checkMove , doNextBalance , tryBalance , compCV , compCVNodes , compDetailedCV , printStats , iMoveToJob -- * IAllocator functions , genAllocNodes , tryAlloc , tryMGAlloc , tryNodeEvac , tryChangeGroup , collapseFailures , allocList -- * Allocation functions , iterateAlloc , tieredAlloc -- * Node group functions , instanceGroup , findSplitInstances , splitCluster ) where import Control.Applicative (liftA2) import Control.Arrow ((&&&)) import qualified Data.IntSet as IntSet import Data.List import Data.Maybe (fromJust, fromMaybe, isJust, isNothing) import Data.Ord (comparing) import Text.Printf (printf) import Ganeti.BasicTypes import qualified Ganeti.HTools.Container as Container import qualified Ganeti.HTools.Instance as Instance import qualified Ganeti.HTools.Nic as Nic import qualified Ganeti.HTools.Node as Node import qualified Ganeti.HTools.Group as Group import Ganeti.HTools.Types import Ganeti.Compat import qualified Ganeti.OpCodes as OpCodes import Ganeti.Utils import Ganeti.Types (mkNonEmpty) -- * Types -- | Allocation\/relocation solution. data AllocSolution = AllocSolution { asFailures :: [FailMode] -- ^ Failure counts , asAllocs :: Int -- ^ Good allocation count , asSolution :: Maybe Node.AllocElement -- ^ The actual allocation result , asLog :: [String] -- ^ Informational messages } -- | Node evacuation/group change iallocator result type. This result -- type consists of actual opcodes (a restricted subset) that are -- transmitted back to Ganeti. data EvacSolution = EvacSolution { esMoved :: [(Idx, Gdx, [Ndx])] -- ^ Instances moved successfully , esFailed :: [(Idx, String)] -- ^ Instances which were not -- relocated , esOpCodes :: [[OpCodes.OpCode]] -- ^ List of jobs } deriving (Show) -- | Allocation results, as used in 'iterateAlloc' and 'tieredAlloc'. type AllocResult = (FailStats, Node.List, Instance.List, [Instance.Instance], [CStats]) -- | Type alias for easier handling. type AllocSolutionList = [(Instance.Instance, AllocSolution)] -- | A type denoting the valid allocation mode/pairs. -- -- For a one-node allocation, this will be a @Left ['Ndx']@, whereas -- for a two-node allocation, this will be a @Right [('Ndx', -- ['Ndx'])]@. In the latter case, the list is basically an -- association list, grouped by primary node and holding the potential -- secondary nodes in the sub-list. type AllocNodes = Either [Ndx] [(Ndx, [Ndx])] -- | The empty solution we start with when computing allocations. emptyAllocSolution :: AllocSolution emptyAllocSolution = AllocSolution { asFailures = [], asAllocs = 0 , asSolution = Nothing, asLog = [] } -- | The empty evac solution. emptyEvacSolution :: EvacSolution emptyEvacSolution = EvacSolution { esMoved = [] , esFailed = [] , esOpCodes = [] } -- | The complete state for the balancing solution. data Table = Table Node.List Instance.List Score [Placement] deriving (Show) -- | Cluster statistics data type. data CStats = CStats { csFmem :: Integer -- ^ Cluster free mem , csFdsk :: Integer -- ^ Cluster free disk , csFspn :: Integer -- ^ Cluster free spindles , csAmem :: Integer -- ^ Cluster allocatable mem , csAdsk :: Integer -- ^ Cluster allocatable disk , csAcpu :: Integer -- ^ Cluster allocatable cpus , csMmem :: Integer -- ^ Max node allocatable mem , csMdsk :: Integer -- ^ Max node allocatable disk , csMcpu :: Integer -- ^ Max node allocatable cpu , csImem :: Integer -- ^ Instance used mem , csIdsk :: Integer -- ^ Instance used disk , csIspn :: Integer -- ^ Instance used spindles , csIcpu :: Integer -- ^ Instance used cpu , csTmem :: Double -- ^ Cluster total mem , csTdsk :: Double -- ^ Cluster total disk , csTspn :: Double -- ^ Cluster total spindles , csTcpu :: Double -- ^ Cluster total cpus , csVcpu :: Integer -- ^ Cluster total virtual cpus , csNcpu :: Double -- ^ Equivalent to 'csIcpu' but in terms of -- physical CPUs, i.e. normalised used phys CPUs , csXmem :: Integer -- ^ Unnacounted for mem , csNmem :: Integer -- ^ Node own memory , csScore :: Score -- ^ The cluster score , csNinst :: Int -- ^ The total number of instances } deriving (Show) -- | A simple type for allocation functions. type AllocMethod = Node.List -- ^ Node list -> Instance.List -- ^ Instance list -> Maybe Int -- ^ Optional allocation limit -> Instance.Instance -- ^ Instance spec for allocation -> AllocNodes -- ^ Which nodes we should allocate on -> [Instance.Instance] -- ^ Allocated instances -> [CStats] -- ^ Running cluster stats -> Result AllocResult -- ^ Allocation result -- | A simple type for the running solution of evacuations. type EvacInnerState = Either String (Node.List, Instance.Instance, Score, Ndx) -- * Utility functions -- | Verifies the N+1 status and return the affected nodes. verifyN1 :: [Node.Node] -> [Node.Node] verifyN1 = filter Node.failN1 {-| Computes the pair of bad nodes and instances. The bad node list is computed via a simple 'verifyN1' check, and the bad instance list is the list of primary and secondary instances of those nodes. -} computeBadItems :: Node.List -> Instance.List -> ([Node.Node], [Instance.Instance]) computeBadItems nl il = let bad_nodes = verifyN1 $ getOnline nl bad_instances = map (`Container.find` il) . sort . nub $ concatMap (\ n -> Node.sList n ++ Node.pList n) bad_nodes in (bad_nodes, bad_instances) -- | Extracts the node pairs for an instance. This can fail if the -- instance is single-homed. FIXME: this needs to be improved, -- together with the general enhancement for handling non-DRBD moves. instanceNodes :: Node.List -> Instance.Instance -> (Ndx, Ndx, Node.Node, Node.Node) instanceNodes nl inst = let old_pdx = Instance.pNode inst old_sdx = Instance.sNode inst old_p = Container.find old_pdx nl old_s = Container.find old_sdx nl in (old_pdx, old_sdx, old_p, old_s) -- | Zero-initializer for the CStats type. emptyCStats :: CStats emptyCStats = CStats 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -- | Update stats with data from a new node. updateCStats :: CStats -> Node.Node -> CStats updateCStats cs node = let CStats { csFmem = x_fmem, csFdsk = x_fdsk, csAmem = x_amem, csAcpu = x_acpu, csAdsk = x_adsk, csMmem = x_mmem, csMdsk = x_mdsk, csMcpu = x_mcpu, csImem = x_imem, csIdsk = x_idsk, csIcpu = x_icpu, csTmem = x_tmem, csTdsk = x_tdsk, csTcpu = x_tcpu, csVcpu = x_vcpu, csNcpu = x_ncpu, csXmem = x_xmem, csNmem = x_nmem, csNinst = x_ninst, csFspn = x_fspn, csIspn = x_ispn, csTspn = x_tspn } = cs inc_amem = Node.fMem node - Node.rMem node inc_amem' = if inc_amem > 0 then inc_amem else 0 inc_adsk = Node.availDisk node inc_imem = truncate (Node.tMem node) - Node.nMem node - Node.xMem node - Node.fMem node inc_icpu = Node.uCpu node inc_idsk = truncate (Node.tDsk node) - Node.fDsk node inc_ispn = Node.tSpindles node - Node.fSpindles node inc_vcpu = Node.hiCpu node inc_acpu = Node.availCpu node inc_ncpu = fromIntegral (Node.uCpu node) / iPolicyVcpuRatio (Node.iPolicy node) in cs { csFmem = x_fmem + fromIntegral (Node.fMem node) , csFdsk = x_fdsk + fromIntegral (Node.fDsk node) , csFspn = x_fspn + fromIntegral (Node.fSpindles node) , csAmem = x_amem + fromIntegral inc_amem' , csAdsk = x_adsk + fromIntegral inc_adsk , csAcpu = x_acpu + fromIntegral inc_acpu , csMmem = max x_mmem (fromIntegral inc_amem') , csMdsk = max x_mdsk (fromIntegral inc_adsk) , csMcpu = max x_mcpu (fromIntegral inc_acpu) , csImem = x_imem + fromIntegral inc_imem , csIdsk = x_idsk + fromIntegral inc_idsk , csIspn = x_ispn + fromIntegral inc_ispn , csIcpu = x_icpu + fromIntegral inc_icpu , csTmem = x_tmem + Node.tMem node , csTdsk = x_tdsk + Node.tDsk node , csTspn = x_tspn + fromIntegral (Node.tSpindles node) , csTcpu = x_tcpu + Node.tCpu node , csVcpu = x_vcpu + fromIntegral inc_vcpu , csNcpu = x_ncpu + inc_ncpu , csXmem = x_xmem + fromIntegral (Node.xMem node) , csNmem = x_nmem + fromIntegral (Node.nMem node) , csNinst = x_ninst + length (Node.pList node) } -- | Compute the total free disk and memory in the cluster. totalResources :: Node.List -> CStats totalResources nl = let cs = foldl' updateCStats emptyCStats . Container.elems $ nl in cs { csScore = compCV nl } -- | Compute the delta between two cluster state. -- -- This is used when doing allocations, to understand better the -- available cluster resources. The return value is a triple of the -- current used values, the delta that was still allocated, and what -- was left unallocated. computeAllocationDelta :: CStats -> CStats -> AllocStats computeAllocationDelta cini cfin = let CStats {csImem = i_imem, csIdsk = i_idsk, csIcpu = i_icpu, csNcpu = i_ncpu, csIspn = i_ispn } = cini CStats {csImem = f_imem, csIdsk = f_idsk, csIcpu = f_icpu, csTmem = t_mem, csTdsk = t_dsk, csVcpu = f_vcpu, csNcpu = f_ncpu, csTcpu = f_tcpu, csIspn = f_ispn, csTspn = t_spn } = cfin rini = AllocInfo { allocInfoVCpus = fromIntegral i_icpu , allocInfoNCpus = i_ncpu , allocInfoMem = fromIntegral i_imem , allocInfoDisk = fromIntegral i_idsk , allocInfoSpn = fromIntegral i_ispn } rfin = AllocInfo { allocInfoVCpus = fromIntegral (f_icpu - i_icpu) , allocInfoNCpus = f_ncpu - i_ncpu , allocInfoMem = fromIntegral (f_imem - i_imem) , allocInfoDisk = fromIntegral (f_idsk - i_idsk) , allocInfoSpn = fromIntegral (f_ispn - i_ispn) } runa = AllocInfo { allocInfoVCpus = fromIntegral (f_vcpu - f_icpu) , allocInfoNCpus = f_tcpu - f_ncpu , allocInfoMem = truncate t_mem - fromIntegral f_imem , allocInfoDisk = truncate t_dsk - fromIntegral f_idsk , allocInfoSpn = truncate t_spn - fromIntegral f_ispn } in (rini, rfin, runa) -- | The names and weights of the individual elements in the CV list. detailedCVInfo :: [(Double, String)] detailedCVInfo = [ (1, "free_mem_cv") , (1, "free_disk_cv") , (1, "n1_cnt") , (1, "reserved_mem_cv") , (4, "offline_all_cnt") , (16, "offline_pri_cnt") , (1, "vcpu_ratio_cv") , (1, "cpu_load_cv") , (1, "mem_load_cv") , (1, "disk_load_cv") , (1, "net_load_cv") , (2, "pri_tags_score") , (1, "spindles_cv") ] -- | Holds the weights used by 'compCVNodes' for each metric. detailedCVWeights :: [Double] detailedCVWeights = map fst detailedCVInfo -- | Compute the mem and disk covariance. compDetailedCV :: [Node.Node] -> [Double] compDetailedCV all_nodes = let (offline, nodes) = partition Node.offline all_nodes mem_l = map Node.pMem nodes dsk_l = map Node.pDsk nodes -- metric: memory covariance mem_cv = stdDev mem_l -- metric: disk covariance dsk_cv = stdDev dsk_l -- metric: count of instances living on N1 failing nodes n1_score = fromIntegral . sum . map (\n -> length (Node.sList n) + length (Node.pList n)) . filter Node.failN1 $ nodes :: Double res_l = map Node.pRem nodes -- metric: reserved memory covariance res_cv = stdDev res_l -- offline instances metrics offline_ipri = sum . map (length . Node.pList) $ offline offline_isec = sum . map (length . Node.sList) $ offline -- metric: count of instances on offline nodes off_score = fromIntegral (offline_ipri + offline_isec)::Double -- metric: count of primary instances on offline nodes (this -- helps with evacuation/failover of primary instances on -- 2-node clusters with one node offline) off_pri_score = fromIntegral offline_ipri::Double cpu_l = map Node.pCpu nodes -- metric: covariance of vcpu/pcpu ratio cpu_cv = stdDev cpu_l -- metrics: covariance of cpu, memory, disk and network load (c_load, m_load, d_load, n_load) = unzip4 $ map (\n -> let DynUtil c1 m1 d1 n1 = Node.utilLoad n DynUtil c2 m2 d2 n2 = Node.utilPool n in (c1/c2, m1/m2, d1/d2, n1/n2)) nodes -- metric: conflicting instance count pri_tags_inst = sum $ map Node.conflictingPrimaries nodes pri_tags_score = fromIntegral pri_tags_inst::Double -- metric: spindles % spindles_cv = map (\n -> Node.instSpindles n / Node.hiSpindles n) nodes in [ mem_cv, dsk_cv, n1_score, res_cv, off_score, off_pri_score, cpu_cv , stdDev c_load, stdDev m_load , stdDev d_load, stdDev n_load , pri_tags_score, stdDev spindles_cv ] -- | Compute the /total/ variance. compCVNodes :: [Node.Node] -> Double compCVNodes = sum . zipWith (*) detailedCVWeights . compDetailedCV -- | Wrapper over 'compCVNodes' for callers that have a 'Node.List'. compCV :: Node.List -> Double compCV = compCVNodes . Container.elems -- | Compute online nodes from a 'Node.List'. getOnline :: Node.List -> [Node.Node] getOnline = filter (not . Node.offline) . Container.elems -- * Balancing functions -- | Compute best table. Note that the ordering of the arguments is important. compareTables :: Table -> Table -> Table compareTables a@(Table _ _ a_cv _) b@(Table _ _ b_cv _ ) = if a_cv > b_cv then b else a -- | Applies an instance move to a given node list and instance. applyMove :: Node.List -> Instance.Instance -> IMove -> OpResult (Node.List, Instance.Instance, Ndx, Ndx) -- Failover (f) applyMove nl inst Failover = let (old_pdx, old_sdx, old_p, old_s) = instanceNodes nl inst int_p = Node.removePri old_p inst int_s = Node.removeSec old_s inst new_nl = do -- Maybe monad new_p <- Node.addPriEx (Node.offline old_p) int_s inst new_s <- Node.addSec int_p inst old_sdx let new_inst = Instance.setBoth inst old_sdx old_pdx return (Container.addTwo old_pdx new_s old_sdx new_p nl, new_inst, old_sdx, old_pdx) in new_nl -- Failover to any (fa) applyMove nl inst (FailoverToAny new_pdx) = do let (old_pdx, old_sdx, old_pnode, _) = instanceNodes nl inst new_pnode = Container.find new_pdx nl force_failover = Node.offline old_pnode new_pnode' <- Node.addPriEx force_failover new_pnode inst let old_pnode' = Node.removePri old_pnode inst inst' = Instance.setPri inst new_pdx nl' = Container.addTwo old_pdx old_pnode' new_pdx new_pnode' nl return (nl', inst', new_pdx, old_sdx) -- Replace the primary (f:, r:np, f) applyMove nl inst (ReplacePrimary new_pdx) = let (old_pdx, old_sdx, old_p, old_s) = instanceNodes nl inst tgt_n = Container.find new_pdx nl int_p = Node.removePri old_p inst int_s = Node.removeSec old_s inst force_p = Node.offline old_p new_nl = do -- Maybe monad -- check that the current secondary can host the instance -- during the migration tmp_s <- Node.addPriEx force_p int_s inst let tmp_s' = Node.removePri tmp_s inst new_p <- Node.addPriEx force_p tgt_n inst new_s <- Node.addSecEx force_p tmp_s' inst new_pdx let new_inst = Instance.setPri inst new_pdx return (Container.add new_pdx new_p $ Container.addTwo old_pdx int_p old_sdx new_s nl, new_inst, new_pdx, old_sdx) in new_nl -- Replace the secondary (r:ns) applyMove nl inst (ReplaceSecondary new_sdx) = let old_pdx = Instance.pNode inst old_sdx = Instance.sNode inst old_s = Container.find old_sdx nl tgt_n = Container.find new_sdx nl int_s = Node.removeSec old_s inst force_s = Node.offline old_s new_inst = Instance.setSec inst new_sdx new_nl = Node.addSecEx force_s tgt_n inst old_pdx >>= \new_s -> return (Container.addTwo new_sdx new_s old_sdx int_s nl, new_inst, old_pdx, new_sdx) in new_nl -- Replace the secondary and failover (r:np, f) applyMove nl inst (ReplaceAndFailover new_pdx) = let (old_pdx, old_sdx, old_p, old_s) = instanceNodes nl inst tgt_n = Container.find new_pdx nl int_p = Node.removePri old_p inst int_s = Node.removeSec old_s inst force_s = Node.offline old_s new_nl = do -- Maybe monad new_p <- Node.addPri tgt_n inst new_s <- Node.addSecEx force_s int_p inst new_pdx let new_inst = Instance.setBoth inst new_pdx old_pdx return (Container.add new_pdx new_p $ Container.addTwo old_pdx new_s old_sdx int_s nl, new_inst, new_pdx, old_pdx) in new_nl -- Failver and replace the secondary (f, r:ns) applyMove nl inst (FailoverAndReplace new_sdx) = let (old_pdx, old_sdx, old_p, old_s) = instanceNodes nl inst tgt_n = Container.find new_sdx nl int_p = Node.removePri old_p inst int_s = Node.removeSec old_s inst force_p = Node.offline old_p new_nl = do -- Maybe monad new_p <- Node.addPriEx force_p int_s inst new_s <- Node.addSecEx force_p tgt_n inst old_sdx let new_inst = Instance.setBoth inst old_sdx new_sdx return (Container.add new_sdx new_s $ Container.addTwo old_sdx new_p old_pdx int_p nl, new_inst, old_sdx, new_sdx) in new_nl -- | Tries to allocate an instance on one given node. allocateOnSingle :: Node.List -> Instance.Instance -> Ndx -> OpResult Node.AllocElement allocateOnSingle nl inst new_pdx = let p = Container.find new_pdx nl new_inst = Instance.setBoth inst new_pdx Node.noSecondary in do Instance.instMatchesPolicy inst (Node.iPolicy p) (Node.exclStorage p) new_p <- Node.addPri p inst let new_nl = Container.add new_pdx new_p nl new_score = compCV new_nl return (new_nl, new_inst, [new_p], new_score) -- | Tries to allocate an instance on a given pair of nodes. allocateOnPair :: Node.List -> Instance.Instance -> Ndx -> Ndx -> OpResult Node.AllocElement allocateOnPair nl inst new_pdx new_sdx = let tgt_p = Container.find new_pdx nl tgt_s = Container.find new_sdx nl in do Instance.instMatchesPolicy inst (Node.iPolicy tgt_p) (Node.exclStorage tgt_p) new_p <- Node.addPri tgt_p inst new_s <- Node.addSec tgt_s inst new_pdx let new_inst = Instance.setBoth inst new_pdx new_sdx new_nl = Container.addTwo new_pdx new_p new_sdx new_s nl return (new_nl, new_inst, [new_p, new_s], compCV new_nl) -- | Tries to perform an instance move and returns the best table -- between the original one and the new one. checkSingleStep :: Table -- ^ The original table -> Instance.Instance -- ^ The instance to move -> Table -- ^ The current best table -> IMove -- ^ The move to apply -> Table -- ^ The final best table checkSingleStep ini_tbl target cur_tbl move = let Table ini_nl ini_il _ ini_plc = ini_tbl tmp_resu = applyMove ini_nl target move in case tmp_resu of Bad _ -> cur_tbl Ok (upd_nl, new_inst, pri_idx, sec_idx) -> let tgt_idx = Instance.idx target upd_cvar = compCV upd_nl upd_il = Container.add tgt_idx new_inst ini_il upd_plc = (tgt_idx, pri_idx, sec_idx, move, upd_cvar):ini_plc upd_tbl = Table upd_nl upd_il upd_cvar upd_plc in compareTables cur_tbl upd_tbl -- | Given the status of the current secondary as a valid new node and -- the current candidate target node, generate the possible moves for -- a instance. possibleMoves :: MirrorType -- ^ The mirroring type of the instance -> Bool -- ^ Whether the secondary node is a valid new node -> Bool -- ^ Whether we can change the primary node -> Ndx -- ^ Target node candidate -> [IMove] -- ^ List of valid result moves possibleMoves MirrorNone _ _ _ = [] possibleMoves MirrorExternal _ False _ = [] possibleMoves MirrorExternal _ True tdx = [ FailoverToAny tdx ] possibleMoves MirrorInternal _ False tdx = [ ReplaceSecondary tdx ] possibleMoves MirrorInternal True True tdx = [ ReplaceSecondary tdx , ReplaceAndFailover tdx , ReplacePrimary tdx , FailoverAndReplace tdx ] possibleMoves MirrorInternal False True tdx = [ ReplaceSecondary tdx , ReplaceAndFailover tdx ] -- | Compute the best move for a given instance. checkInstanceMove :: [Ndx] -- ^ Allowed target node indices -> Bool -- ^ Whether disk moves are allowed -> Bool -- ^ Whether instance moves are allowed -> Table -- ^ Original table -> Instance.Instance -- ^ Instance to move -> Table -- ^ Best new table for this instance checkInstanceMove nodes_idx disk_moves inst_moves ini_tbl target = let opdx = Instance.pNode target osdx = Instance.sNode target bad_nodes = [opdx, osdx] nodes = filter (`notElem` bad_nodes) nodes_idx mir_type = Instance.mirrorType target use_secondary = elem osdx nodes_idx && inst_moves aft_failover = if mir_type == MirrorInternal && use_secondary -- if drbd and allowed to failover then checkSingleStep ini_tbl target ini_tbl Failover else ini_tbl all_moves = if disk_moves then concatMap (possibleMoves mir_type use_secondary inst_moves) nodes else [] in -- iterate over the possible nodes for this instance foldl' (checkSingleStep ini_tbl target) aft_failover all_moves -- | Compute the best next move. checkMove :: [Ndx] -- ^ Allowed target node indices -> Bool -- ^ Whether disk moves are allowed -> Bool -- ^ Whether instance moves are allowed -> Table -- ^ The current solution -> [Instance.Instance] -- ^ List of instances still to move -> Table -- ^ The new solution checkMove nodes_idx disk_moves inst_moves ini_tbl victims = let Table _ _ _ ini_plc = ini_tbl -- we're using rwhnf from the Control.Parallel.Strategies -- package; we don't need to use rnf as that would force too -- much evaluation in single-threaded cases, and in -- multi-threaded case the weak head normal form is enough to -- spark the evaluation tables = parMap rwhnf (checkInstanceMove nodes_idx disk_moves inst_moves ini_tbl) victims -- iterate over all instances, computing the best move best_tbl = foldl' compareTables ini_tbl tables Table _ _ _ best_plc = best_tbl in if length best_plc == length ini_plc then ini_tbl -- no advancement else best_tbl -- | Check if we are allowed to go deeper in the balancing. doNextBalance :: Table -- ^ The starting table -> Int -- ^ Remaining length -> Score -- ^ Score at which to stop -> Bool -- ^ The resulting table and commands doNextBalance ini_tbl max_rounds min_score = let Table _ _ ini_cv ini_plc = ini_tbl ini_plc_len = length ini_plc in (max_rounds < 0 || ini_plc_len < max_rounds) && ini_cv > min_score -- | Run a balance move. tryBalance :: Table -- ^ The starting table -> Bool -- ^ Allow disk moves -> Bool -- ^ Allow instance moves -> Bool -- ^ Only evacuate moves -> Score -- ^ Min gain threshold -> Score -- ^ Min gain -> Maybe Table -- ^ The resulting table and commands tryBalance ini_tbl disk_moves inst_moves evac_mode mg_limit min_gain = let Table ini_nl ini_il ini_cv _ = ini_tbl all_inst = Container.elems ini_il all_nodes = Container.elems ini_nl (offline_nodes, online_nodes) = partition Node.offline all_nodes all_inst' = if evac_mode then let bad_nodes = map Node.idx offline_nodes in filter (any (`elem` bad_nodes) . Instance.allNodes) all_inst else all_inst reloc_inst = filter (\i -> Instance.movable i && Instance.autoBalance i) all_inst' node_idx = map Node.idx online_nodes fin_tbl = checkMove node_idx disk_moves inst_moves ini_tbl reloc_inst (Table _ _ fin_cv _) = fin_tbl in if fin_cv < ini_cv && (ini_cv > mg_limit || ini_cv - fin_cv >= min_gain) then Just fin_tbl -- this round made success, return the new table else Nothing -- * Allocation functions -- | Build failure stats out of a list of failures. collapseFailures :: [FailMode] -> FailStats collapseFailures flst = map (\k -> (k, foldl' (\a e -> if e == k then a + 1 else a) 0 flst)) [minBound..maxBound] -- | Compares two Maybe AllocElement and chooses the best score. bestAllocElement :: Maybe Node.AllocElement -> Maybe Node.AllocElement -> Maybe Node.AllocElement bestAllocElement a Nothing = a bestAllocElement Nothing b = b bestAllocElement a@(Just (_, _, _, ascore)) b@(Just (_, _, _, bscore)) = if ascore < bscore then a else b -- | Update current Allocation solution and failure stats with new -- elements. concatAllocs :: AllocSolution -> OpResult Node.AllocElement -> AllocSolution concatAllocs as (Bad reason) = as { asFailures = reason : asFailures as } concatAllocs as (Ok ns) = let -- Choose the old or new solution, based on the cluster score cntok = asAllocs as osols = asSolution as nsols = bestAllocElement osols (Just ns) nsuc = cntok + 1 -- Note: we force evaluation of nsols here in order to keep the -- memory profile low - we know that we will need nsols for sure -- in the next cycle, so we force evaluation of nsols, since the -- foldl' in the caller will only evaluate the tuple, but not the -- elements of the tuple in nsols `seq` nsuc `seq` as { asAllocs = nsuc, asSolution = nsols } -- | Sums two 'AllocSolution' structures. sumAllocs :: AllocSolution -> AllocSolution -> AllocSolution sumAllocs (AllocSolution aFails aAllocs aSols aLog) (AllocSolution bFails bAllocs bSols bLog) = -- note: we add b first, since usually it will be smaller; when -- fold'ing, a will grow and grow whereas b is the per-group -- result, hence smaller let nFails = bFails ++ aFails nAllocs = aAllocs + bAllocs nSols = bestAllocElement aSols bSols nLog = bLog ++ aLog in AllocSolution nFails nAllocs nSols nLog -- | Given a solution, generates a reasonable description for it. describeSolution :: AllocSolution -> String describeSolution as = let fcnt = asFailures as sols = asSolution as freasons = intercalate ", " . map (\(a, b) -> printf "%s: %d" (show a) b) . filter ((> 0) . snd) . collapseFailures $ fcnt in case sols of Nothing -> "No valid allocation solutions, failure reasons: " ++ (if null fcnt then "unknown reasons" else freasons) Just (_, _, nodes, cv) -> printf ("score: %.8f, successes %d, failures %d (%s)" ++ " for node(s) %s") cv (asAllocs as) (length fcnt) freasons (intercalate "/" . map Node.name $ nodes) -- | Annotates a solution with the appropriate string. annotateSolution :: AllocSolution -> AllocSolution annotateSolution as = as { asLog = describeSolution as : asLog as } -- | Reverses an evacuation solution. -- -- Rationale: we always concat the results to the top of the lists, so -- for proper jobset execution, we should reverse all lists. reverseEvacSolution :: EvacSolution -> EvacSolution reverseEvacSolution (EvacSolution f m o) = EvacSolution (reverse f) (reverse m) (reverse o) -- | Generate the valid node allocation singles or pairs for a new instance. genAllocNodes :: Group.List -- ^ Group list -> Node.List -- ^ The node map -> Int -- ^ The number of nodes required -> Bool -- ^ Whether to drop or not -- unallocable nodes -> Result AllocNodes -- ^ The (monadic) result genAllocNodes gl nl count drop_unalloc = let filter_fn = if drop_unalloc then filter (Group.isAllocable . flip Container.find gl . Node.group) else id all_nodes = filter_fn $ getOnline nl all_pairs = [(Node.idx p, [Node.idx s | s <- all_nodes, Node.idx p /= Node.idx s, Node.group p == Node.group s]) | p <- all_nodes] in case count of 1 -> Ok (Left (map Node.idx all_nodes)) 2 -> Ok (Right (filter (not . null . snd) all_pairs)) _ -> Bad "Unsupported number of nodes, only one or two supported" -- | Try to allocate an instance on the cluster. tryAlloc :: (Monad m) => Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> Instance.Instance -- ^ The instance to allocate -> AllocNodes -- ^ The allocation targets -> m AllocSolution -- ^ Possible solution list tryAlloc _ _ _ (Right []) = fail "Not enough online nodes" tryAlloc nl _ inst (Right ok_pairs) = let psols = parMap rwhnf (\(p, ss) -> foldl' (\cstate -> concatAllocs cstate . allocateOnPair nl inst p) emptyAllocSolution ss) ok_pairs sols = foldl' sumAllocs emptyAllocSolution psols in return $ annotateSolution sols tryAlloc _ _ _ (Left []) = fail "No online nodes" tryAlloc nl _ inst (Left all_nodes) = let sols = foldl' (\cstate -> concatAllocs cstate . allocateOnSingle nl inst ) emptyAllocSolution all_nodes in return $ annotateSolution sols -- | Given a group/result, describe it as a nice (list of) messages. solutionDescription :: (Group.Group, Result AllocSolution) -> [String] solutionDescription (grp, result) = case result of Ok solution -> map (printf "Group %s (%s): %s" gname pol) (asLog solution) Bad message -> [printf "Group %s: error %s" gname message] where gname = Group.name grp pol = allocPolicyToRaw (Group.allocPolicy grp) -- | From a list of possibly bad and possibly empty solutions, filter -- only the groups with a valid result. Note that the result will be -- reversed compared to the original list. filterMGResults :: [(Group.Group, Result AllocSolution)] -> [(Group.Group, AllocSolution)] filterMGResults = foldl' fn [] where unallocable = not . Group.isAllocable fn accu (grp, rasol) = case rasol of Bad _ -> accu Ok sol | isNothing (asSolution sol) -> accu | unallocable grp -> accu | otherwise -> (grp, sol):accu -- | Sort multigroup results based on policy and score. sortMGResults :: [(Group.Group, AllocSolution)] -> [(Group.Group, AllocSolution)] sortMGResults sols = let extractScore (_, _, _, x) = x solScore (grp, sol) = (Group.allocPolicy grp, (extractScore . fromJust . asSolution) sol) in sortBy (comparing solScore) sols -- | Removes node groups which can't accommodate the instance filterValidGroups :: [(Group.Group, (Node.List, Instance.List))] -> Instance.Instance -> ([(Group.Group, (Node.List, Instance.List))], [String]) filterValidGroups [] _ = ([], []) filterValidGroups (ng:ngs) inst = let (valid_ngs, msgs) = filterValidGroups ngs inst hasNetwork nic = case Nic.network nic of Just net -> net `elem` Group.networks (fst ng) Nothing -> True hasRequiredNetworks = all hasNetwork (Instance.nics inst) in if hasRequiredNetworks then (ng:valid_ngs, msgs) else (valid_ngs, ("group " ++ Group.name (fst ng) ++ " is not connected to a network required by instance " ++ Instance.name inst):msgs) -- | Finds the best group for an instance on a multi-group cluster. -- -- Only solutions in @preferred@ and @last_resort@ groups will be -- accepted as valid, and additionally if the allowed groups parameter -- is not null then allocation will only be run for those group -- indices. findBestAllocGroup :: Group.List -- ^ The group list -> Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> Maybe [Gdx] -- ^ The allowed groups -> Instance.Instance -- ^ The instance to allocate -> Int -- ^ Required number of nodes -> Result (Group.Group, AllocSolution, [String]) findBestAllocGroup mggl mgnl mgil allowed_gdxs inst cnt = let groups_by_idx = splitCluster mgnl mgil groups = map (\(gid, d) -> (Container.find gid mggl, d)) groups_by_idx groups' = maybe groups (\gs -> filter ((`elem` gs) . Group.idx . fst) groups) allowed_gdxs (groups'', filter_group_msgs) = filterValidGroups groups' inst sols = map (\(gr, (nl, il)) -> (gr, genAllocNodes mggl nl cnt False >>= tryAlloc nl il inst)) groups''::[(Group.Group, Result AllocSolution)] all_msgs = filter_group_msgs ++ concatMap solutionDescription sols goodSols = filterMGResults sols sortedSols = sortMGResults goodSols in case sortedSols of [] -> Bad $ if null groups' then "no groups for evacuation: allowed groups was" ++ show allowed_gdxs ++ ", all groups: " ++ show (map fst groups) else intercalate ", " all_msgs (final_group, final_sol):_ -> return (final_group, final_sol, all_msgs) -- | Try to allocate an instance on a multi-group cluster. tryMGAlloc :: Group.List -- ^ The group list -> Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> Instance.Instance -- ^ The instance to allocate -> Int -- ^ Required number of nodes -> Result AllocSolution -- ^ Possible solution list tryMGAlloc mggl mgnl mgil inst cnt = do (best_group, solution, all_msgs) <- findBestAllocGroup mggl mgnl mgil Nothing inst cnt let group_name = Group.name best_group selmsg = "Selected group: " ++ group_name return $ solution { asLog = selmsg:all_msgs } -- | Calculate the new instance list after allocation solution. updateIl :: Instance.List -- ^ The original instance list -> Maybe Node.AllocElement -- ^ The result of the allocation attempt -> Instance.List -- ^ The updated instance list updateIl il Nothing = il updateIl il (Just (_, xi, _, _)) = Container.add (Container.size il) xi il -- | Extract the the new node list from the allocation solution. extractNl :: Node.List -- ^ The original node list -> Maybe Node.AllocElement -- ^ The result of the allocation attempt -> Node.List -- ^ The new node list extractNl nl Nothing = nl extractNl _ (Just (xnl, _, _, _)) = xnl -- | Try to allocate a list of instances on a multi-group cluster. allocList :: Group.List -- ^ The group list -> Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> [(Instance.Instance, Int)] -- ^ The instance to allocate -> AllocSolutionList -- ^ Possible solution list -> Result (Node.List, Instance.List, AllocSolutionList) -- ^ The final solution list allocList _ nl il [] result = Ok (nl, il, result) allocList gl nl il ((xi, xicnt):xies) result = do ares <- tryMGAlloc gl nl il xi xicnt let sol = asSolution ares nl' = extractNl nl sol il' = updateIl il sol allocList gl nl' il' xies ((xi, ares):result) -- | Function which fails if the requested mode is change secondary. -- -- This is useful since except DRBD, no other disk template can -- execute change secondary; thus, we can just call this function -- instead of always checking for secondary mode. After the call to -- this function, whatever mode we have is just a primary change. failOnSecondaryChange :: (Monad m) => EvacMode -> DiskTemplate -> m () failOnSecondaryChange ChangeSecondary dt = fail $ "Instances with disk template '" ++ diskTemplateToRaw dt ++ "' can't execute change secondary" failOnSecondaryChange _ _ = return () -- | Run evacuation for a single instance. -- -- /Note:/ this function should correctly execute both intra-group -- evacuations (in all modes) and inter-group evacuations (in the -- 'ChangeAll' mode). Of course, this requires that the correct list -- of target nodes is passed. nodeEvacInstance :: Node.List -- ^ The node list (cluster-wide) -> Instance.List -- ^ Instance list (cluster-wide) -> EvacMode -- ^ The evacuation mode -> Instance.Instance -- ^ The instance to be evacuated -> Gdx -- ^ The group we're targetting -> [Ndx] -- ^ The list of available nodes -- for allocation -> Result (Node.List, Instance.List, [OpCodes.OpCode]) nodeEvacInstance nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTDiskless}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly nl il inst gdx avail_nodes nodeEvacInstance _ _ _ (Instance.Instance {Instance.diskTemplate = DTPlain}) _ _ = fail "Instances of type plain cannot be relocated" nodeEvacInstance _ _ _ (Instance.Instance {Instance.diskTemplate = DTFile}) _ _ = fail "Instances of type file cannot be relocated" nodeEvacInstance nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTSharedFile}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly nl il inst gdx avail_nodes nodeEvacInstance nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTBlock}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly nl il inst gdx avail_nodes nodeEvacInstance nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTRbd}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly nl il inst gdx avail_nodes nodeEvacInstance nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTExt}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly nl il inst gdx avail_nodes nodeEvacInstance nl il ChangePrimary inst@(Instance.Instance {Instance.diskTemplate = DTDrbd8}) _ _ = do (nl', inst', _, _) <- opToResult $ applyMove nl inst Failover let idx = Instance.idx inst il' = Container.add idx inst' il ops = iMoveToJob nl' il' idx Failover return (nl', il', ops) nodeEvacInstance nl il ChangeSecondary inst@(Instance.Instance {Instance.diskTemplate = DTDrbd8}) gdx avail_nodes = evacOneNodeOnly nl il inst gdx avail_nodes -- The algorithm for ChangeAll is as follows: -- -- * generate all (primary, secondary) node pairs for the target groups -- * for each pair, execute the needed moves (r:s, f, r:s) and compute -- the final node list state and group score -- * select the best choice via a foldl that uses the same Either -- String solution as the ChangeSecondary mode nodeEvacInstance nl il ChangeAll inst@(Instance.Instance {Instance.diskTemplate = DTDrbd8}) gdx avail_nodes = do let no_nodes = Left "no nodes available" node_pairs = [(p,s) | p <- avail_nodes, s <- avail_nodes, p /= s] (nl', il', ops, _) <- annotateResult "Can't find any good nodes for relocation" . eitherToResult $ foldl' (\accu nodes -> case evacDrbdAllInner nl il inst gdx nodes of Bad msg -> case accu of Right _ -> accu -- we don't need more details (which -- nodes, etc.) as we only selected -- this group if we can allocate on -- it, hence failures will not -- propagate out of this fold loop Left _ -> Left $ "Allocation failed: " ++ msg Ok result@(_, _, _, new_cv) -> let new_accu = Right result in case accu of Left _ -> new_accu Right (_, _, _, old_cv) -> if old_cv < new_cv then accu else new_accu ) no_nodes node_pairs return (nl', il', ops) -- | Generic function for changing one node of an instance. -- -- This is similar to 'nodeEvacInstance' but will be used in a few of -- its sub-patterns. It folds the inner function 'evacOneNodeInner' -- over the list of available nodes, which results in the best choice -- for relocation. evacOneNodeOnly :: Node.List -- ^ The node list (cluster-wide) -> Instance.List -- ^ Instance list (cluster-wide) -> Instance.Instance -- ^ The instance to be evacuated -> Gdx -- ^ The group we're targetting -> [Ndx] -- ^ The list of available nodes -- for allocation -> Result (Node.List, Instance.List, [OpCodes.OpCode]) evacOneNodeOnly nl il inst gdx avail_nodes = do op_fn <- case Instance.mirrorType inst of MirrorNone -> Bad "Can't relocate/evacuate non-mirrored instances" MirrorInternal -> Ok ReplaceSecondary MirrorExternal -> Ok FailoverToAny (nl', inst', _, ndx) <- annotateResult "Can't find any good node" . eitherToResult $ foldl' (evacOneNodeInner nl inst gdx op_fn) (Left "no nodes available") avail_nodes let idx = Instance.idx inst il' = Container.add idx inst' il ops = iMoveToJob nl' il' idx (op_fn ndx) return (nl', il', ops) -- | Inner fold function for changing one node of an instance. -- -- Depending on the instance disk template, this will either change -- the secondary (for DRBD) or the primary node (for shared -- storage). However, the operation is generic otherwise. -- -- The running solution is either a @Left String@, which means we -- don't have yet a working solution, or a @Right (...)@, which -- represents a valid solution; it holds the modified node list, the -- modified instance (after evacuation), the score of that solution, -- and the new secondary node index. evacOneNodeInner :: Node.List -- ^ Cluster node list -> Instance.Instance -- ^ Instance being evacuated -> Gdx -- ^ The group index of the instance -> (Ndx -> IMove) -- ^ Operation constructor -> EvacInnerState -- ^ Current best solution -> Ndx -- ^ Node we're evaluating as target -> EvacInnerState -- ^ New best solution evacOneNodeInner nl inst gdx op_fn accu ndx = case applyMove nl inst (op_fn ndx) of Bad fm -> let fail_msg = "Node " ++ Container.nameOf nl ndx ++ " failed: " ++ show fm in either (const $ Left fail_msg) (const accu) accu Ok (nl', inst', _, _) -> let nodes = Container.elems nl' -- The fromJust below is ugly (it can fail nastily), but -- at this point we should have any internal mismatches, -- and adding a monad here would be quite involved grpnodes = fromJust (gdx `lookup` Node.computeGroups nodes) new_cv = compCVNodes grpnodes new_accu = Right (nl', inst', new_cv, ndx) in case accu of Left _ -> new_accu Right (_, _, old_cv, _) -> if old_cv < new_cv then accu else new_accu -- | Compute result of changing all nodes of a DRBD instance. -- -- Given the target primary and secondary node (which might be in a -- different group or not), this function will 'execute' all the -- required steps and assuming all operations succceed, will return -- the modified node and instance lists, the opcodes needed for this -- and the new group score. evacDrbdAllInner :: Node.List -- ^ Cluster node list -> Instance.List -- ^ Cluster instance list -> Instance.Instance -- ^ The instance to be moved -> Gdx -- ^ The target group index -- (which can differ from the -- current group of the -- instance) -> (Ndx, Ndx) -- ^ Tuple of new -- primary\/secondary nodes -> Result (Node.List, Instance.List, [OpCodes.OpCode], Score) evacDrbdAllInner nl il inst gdx (t_pdx, t_sdx) = do let primary = Container.find (Instance.pNode inst) nl idx = Instance.idx inst -- if the primary is offline, then we first failover (nl1, inst1, ops1) <- if Node.offline primary then do (nl', inst', _, _) <- annotateResult "Failing over to the secondary" . opToResult $ applyMove nl inst Failover return (nl', inst', [Failover]) else return (nl, inst, []) let (o1, o2, o3) = (ReplaceSecondary t_pdx, Failover, ReplaceSecondary t_sdx) -- we now need to execute a replace secondary to the future -- primary node (nl2, inst2, _, _) <- annotateResult "Changing secondary to new primary" . opToResult $ applyMove nl1 inst1 o1 let ops2 = o1:ops1 -- we now execute another failover, the primary stays fixed now (nl3, inst3, _, _) <- annotateResult "Failing over to new primary" . opToResult $ applyMove nl2 inst2 o2 let ops3 = o2:ops2 -- and finally another replace secondary, to the final secondary (nl4, inst4, _, _) <- annotateResult "Changing secondary to final secondary" . opToResult $ applyMove nl3 inst3 o3 let ops4 = o3:ops3 il' = Container.add idx inst4 il ops = concatMap (iMoveToJob nl4 il' idx) $ reverse ops4 let nodes = Container.elems nl4 -- The fromJust below is ugly (it can fail nastily), but -- at this point we should have any internal mismatches, -- and adding a monad here would be quite involved grpnodes = fromJust (gdx `lookup` Node.computeGroups nodes) new_cv = compCVNodes grpnodes return (nl4, il', ops, new_cv) -- | Computes the nodes in a given group which are available for -- allocation. availableGroupNodes :: [(Gdx, [Ndx])] -- ^ Group index/node index assoc list -> IntSet.IntSet -- ^ Nodes that are excluded -> Gdx -- ^ The group for which we -- query the nodes -> Result [Ndx] -- ^ List of available node indices availableGroupNodes group_nodes excl_ndx gdx = do local_nodes <- maybe (Bad $ "Can't find group with index " ++ show gdx) Ok (lookup gdx group_nodes) let avail_nodes = filter (not . flip IntSet.member excl_ndx) local_nodes return avail_nodes -- | Updates the evac solution with the results of an instance -- evacuation. updateEvacSolution :: (Node.List, Instance.List, EvacSolution) -> Idx -> Result (Node.List, Instance.List, [OpCodes.OpCode]) -> (Node.List, Instance.List, EvacSolution) updateEvacSolution (nl, il, es) idx (Bad msg) = (nl, il, es { esFailed = (idx, msg):esFailed es}) updateEvacSolution (_, _, es) idx (Ok (nl, il, opcodes)) = (nl, il, es { esMoved = new_elem:esMoved es , esOpCodes = opcodes:esOpCodes es }) where inst = Container.find idx il new_elem = (idx, instancePriGroup nl inst, Instance.allNodes inst) -- | Node-evacuation IAllocator mode main function. tryNodeEvac :: Group.List -- ^ The cluster groups -> Node.List -- ^ The node list (cluster-wide, not per group) -> Instance.List -- ^ Instance list (cluster-wide) -> EvacMode -- ^ The evacuation mode -> [Idx] -- ^ List of instance (indices) to be evacuated -> Result (Node.List, Instance.List, EvacSolution) tryNodeEvac _ ini_nl ini_il mode idxs = let evac_ndx = nodesToEvacuate ini_il mode idxs offline = map Node.idx . filter Node.offline $ Container.elems ini_nl excl_ndx = foldl' (flip IntSet.insert) evac_ndx offline group_ndx = map (\(gdx, (nl, _)) -> (gdx, map Node.idx (Container.elems nl))) $ splitCluster ini_nl ini_il (fin_nl, fin_il, esol) = foldl' (\state@(nl, il, _) inst -> let gdx = instancePriGroup nl inst pdx = Instance.pNode inst in updateEvacSolution state (Instance.idx inst) $ availableGroupNodes group_ndx (IntSet.insert pdx excl_ndx) gdx >>= nodeEvacInstance nl il mode inst gdx ) (ini_nl, ini_il, emptyEvacSolution) (map (`Container.find` ini_il) idxs) in return (fin_nl, fin_il, reverseEvacSolution esol) -- | Change-group IAllocator mode main function. -- -- This is very similar to 'tryNodeEvac', the only difference is that -- we don't choose as target group the current instance group, but -- instead: -- -- 1. at the start of the function, we compute which are the target -- groups; either no groups were passed in, in which case we choose -- all groups out of which we don't evacuate instance, or there were -- some groups passed, in which case we use those -- -- 2. for each instance, we use 'findBestAllocGroup' to choose the -- best group to hold the instance, and then we do what -- 'tryNodeEvac' does, except for this group instead of the current -- instance group. -- -- Note that the correct behaviour of this function relies on the -- function 'nodeEvacInstance' to be able to do correctly both -- intra-group and inter-group moves when passed the 'ChangeAll' mode. tryChangeGroup :: Group.List -- ^ The cluster groups -> Node.List -- ^ The node list (cluster-wide) -> Instance.List -- ^ Instance list (cluster-wide) -> [Gdx] -- ^ Target groups; if empty, any -- groups not being evacuated -> [Idx] -- ^ List of instance (indices) to be evacuated -> Result (Node.List, Instance.List, EvacSolution) tryChangeGroup gl ini_nl ini_il gdxs idxs = let evac_gdxs = nub $ map (instancePriGroup ini_nl . flip Container.find ini_il) idxs target_gdxs = (if null gdxs then Container.keys gl else gdxs) \\ evac_gdxs offline = map Node.idx . filter Node.offline $ Container.elems ini_nl excl_ndx = foldl' (flip IntSet.insert) IntSet.empty offline group_ndx = map (\(gdx, (nl, _)) -> (gdx, map Node.idx (Container.elems nl))) $ splitCluster ini_nl ini_il (fin_nl, fin_il, esol) = foldl' (\state@(nl, il, _) inst -> let solution = do let ncnt = Instance.requiredNodes $ Instance.diskTemplate inst (grp, _, _) <- findBestAllocGroup gl nl il (Just target_gdxs) inst ncnt let gdx = Group.idx grp av_nodes <- availableGroupNodes group_ndx excl_ndx gdx nodeEvacInstance nl il ChangeAll inst gdx av_nodes in updateEvacSolution state (Instance.idx inst) solution ) (ini_nl, ini_il, emptyEvacSolution) (map (`Container.find` ini_il) idxs) in return (fin_nl, fin_il, reverseEvacSolution esol) -- | Standard-sized allocation method. -- -- This places instances of the same size on the cluster until we're -- out of space. The result will be a list of identically-sized -- instances. iterateAlloc :: AllocMethod iterateAlloc nl il limit newinst allocnodes ixes cstats = let depth = length ixes newname = printf "new-%d" depth::String newidx = Container.size il newi2 = Instance.setIdx (Instance.setName newinst newname) newidx newlimit = fmap (flip (-) 1) limit in case tryAlloc nl il newi2 allocnodes of Bad s -> Bad s Ok (AllocSolution { asFailures = errs, asSolution = sols3 }) -> let newsol = Ok (collapseFailures errs, nl, il, ixes, cstats) in case sols3 of Nothing -> newsol Just (xnl, xi, _, _) -> if limit == Just 0 then newsol else iterateAlloc xnl (Container.add newidx xi il) newlimit newinst allocnodes (xi:ixes) (totalResources xnl:cstats) -- | Predicate whether shrinking a single resource can lead to a valid -- allocation. sufficesShrinking :: (Instance.Instance -> AllocSolution) -> Instance.Instance -> FailMode -> Maybe Instance.Instance sufficesShrinking allocFn inst fm = case dropWhile (isNothing . asSolution . fst) . takeWhile (liftA2 (||) (elem fm . asFailures . fst) (isJust . asSolution . fst)) . map (allocFn &&& id) $ iterateOk (`Instance.shrinkByType` fm) inst of x:_ -> Just . snd $ x _ -> Nothing -- | Tiered allocation method. -- -- This places instances on the cluster, and decreases the spec until -- we can allocate again. The result will be a list of decreasing -- instance specs. tieredAlloc :: AllocMethod tieredAlloc nl il limit newinst allocnodes ixes cstats = case iterateAlloc nl il limit newinst allocnodes ixes cstats of Bad s -> Bad s Ok (errs, nl', il', ixes', cstats') -> let newsol = Ok (errs, nl', il', ixes', cstats') ixes_cnt = length ixes' (stop, newlimit) = case limit of Nothing -> (False, Nothing) Just n -> (n <= ixes_cnt, Just (n - ixes_cnt)) sortedErrs = map fst $ sortBy (comparing snd) errs suffShrink = sufficesShrinking (fromMaybe emptyAllocSolution . flip (tryAlloc nl' il') allocnodes) newinst bigSteps = filter isJust . map suffShrink . reverse $ sortedErrs in if stop then newsol else case bigSteps of Just newinst':_ -> tieredAlloc nl' il' newlimit newinst' allocnodes ixes' cstats' _ -> case Instance.shrinkByType newinst . last $ sortedErrs of Bad _ -> newsol Ok newinst' -> tieredAlloc nl' il' newlimit newinst' allocnodes ixes' cstats' -- * Formatting functions -- | Given the original and final nodes, computes the relocation description. computeMoves :: Instance.Instance -- ^ The instance to be moved -> String -- ^ The instance name -> IMove -- ^ The move being performed -> String -- ^ New primary -> String -- ^ New secondary -> (String, [String]) -- ^ Tuple of moves and commands list; moves is containing -- either @/f/@ for failover or @/r:name/@ for replace -- secondary, while the command list holds gnt-instance -- commands (without that prefix), e.g \"@failover instance1@\" computeMoves i inam mv c d = case mv of Failover -> ("f", [mig]) FailoverToAny _ -> (printf "fa:%s" c, [mig_any]) FailoverAndReplace _ -> (printf "f r:%s" d, [mig, rep d]) ReplaceSecondary _ -> (printf "r:%s" d, [rep d]) ReplaceAndFailover _ -> (printf "r:%s f" c, [rep c, mig]) ReplacePrimary _ -> (printf "f r:%s f" c, [mig, rep c, mig]) where morf = if Instance.isRunning i then "migrate" else "failover" mig = printf "%s -f %s" morf inam::String mig_any = printf "%s -f -n %s %s" morf c inam::String rep n = printf "replace-disks -n %s %s" n inam::String -- | Converts a placement to string format. printSolutionLine :: Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> Int -- ^ Maximum node name length -> Int -- ^ Maximum instance name length -> Placement -- ^ The current placement -> Int -- ^ The index of the placement in -- the solution -> (String, [String]) printSolutionLine nl il nmlen imlen plc pos = let pmlen = (2*nmlen + 1) (i, p, s, mv, c) = plc old_sec = Instance.sNode inst inst = Container.find i il inam = Instance.alias inst npri = Node.alias $ Container.find p nl nsec = Node.alias $ Container.find s nl opri = Node.alias $ Container.find (Instance.pNode inst) nl osec = Node.alias $ Container.find old_sec nl (moves, cmds) = computeMoves inst inam mv npri nsec -- FIXME: this should check instead/also the disk template ostr = if old_sec == Node.noSecondary then printf "%s" opri::String else printf "%s:%s" opri osec::String nstr = if s == Node.noSecondary then printf "%s" npri::String else printf "%s:%s" npri nsec::String in (printf " %3d. %-*s %-*s => %-*s %12.8f a=%s" pos imlen inam pmlen ostr pmlen nstr c moves, cmds) -- | Return the instance and involved nodes in an instance move. -- -- Note that the output list length can vary, and is not required nor -- guaranteed to be of any specific length. involvedNodes :: Instance.List -- ^ Instance list, used for retrieving -- the instance from its index; note -- that this /must/ be the original -- instance list, so that we can -- retrieve the old nodes -> Placement -- ^ The placement we're investigating, -- containing the new nodes and -- instance index -> [Ndx] -- ^ Resulting list of node indices involvedNodes il plc = let (i, np, ns, _, _) = plc inst = Container.find i il in nub $ [np, ns] ++ Instance.allNodes inst -- | Inner function for splitJobs, that either appends the next job to -- the current jobset, or starts a new jobset. mergeJobs :: ([JobSet], [Ndx]) -> MoveJob -> ([JobSet], [Ndx]) mergeJobs ([], _) n@(ndx, _, _, _) = ([[n]], ndx) mergeJobs (cjs@(j:js), nbuf) n@(ndx, _, _, _) | null (ndx `intersect` nbuf) = ((n:j):js, ndx ++ nbuf) | otherwise = ([n]:cjs, ndx) -- | Break a list of moves into independent groups. Note that this -- will reverse the order of jobs. splitJobs :: [MoveJob] -> [JobSet] splitJobs = fst . foldl mergeJobs ([], []) -- | Given a list of commands, prefix them with @gnt-instance@ and -- also beautify the display a little. formatJob :: Int -> Int -> (Int, MoveJob) -> [String] formatJob jsn jsl (sn, (_, _, _, cmds)) = let out = printf " echo job %d/%d" jsn sn: printf " check": map (" gnt-instance " ++) cmds in if sn == 1 then ["", printf "echo jobset %d, %d jobs" jsn jsl] ++ out else out -- | Given a list of commands, prefix them with @gnt-instance@ and -- also beautify the display a little. formatCmds :: [JobSet] -> String formatCmds = unlines . concatMap (\(jsn, js) -> concatMap (formatJob jsn (length js)) (zip [1..] js)) . zip [1..] -- | Print the node list. printNodes :: Node.List -> [String] -> String printNodes nl fs = let fields = case fs of [] -> Node.defaultFields "+":rest -> Node.defaultFields ++ rest _ -> fs snl = sortBy (comparing Node.idx) (Container.elems nl) (header, isnum) = unzip $ map Node.showHeader fields in printTable "" header (map (Node.list fields) snl) isnum -- | Print the instance list. printInsts :: Node.List -> Instance.List -> String printInsts nl il = let sil = sortBy (comparing Instance.idx) (Container.elems il) helper inst = [ if Instance.isRunning inst then "R" else " " , Instance.name inst , Container.nameOf nl (Instance.pNode inst) , let sdx = Instance.sNode inst in if sdx == Node.noSecondary then "" else Container.nameOf nl sdx , if Instance.autoBalance inst then "Y" else "N" , printf "%3d" $ Instance.vcpus inst , printf "%5d" $ Instance.mem inst , printf "%5d" $ Instance.dsk inst `div` 1024 , printf "%5.3f" lC , printf "%5.3f" lM , printf "%5.3f" lD , printf "%5.3f" lN ] where DynUtil lC lM lD lN = Instance.util inst header = [ "F", "Name", "Pri_node", "Sec_node", "Auto_bal" , "vcpu", "mem" , "dsk", "lCpu", "lMem", "lDsk", "lNet" ] isnum = False:False:False:False:False:repeat True in printTable "" header (map helper sil) isnum -- | Shows statistics for a given node list. printStats :: String -> Node.List -> String printStats lp nl = let dcvs = compDetailedCV $ Container.elems nl (weights, names) = unzip detailedCVInfo hd = zip3 (weights ++ repeat 1) (names ++ repeat "unknown") dcvs header = [ "Field", "Value", "Weight" ] formatted = map (\(w, h, val) -> [ h , printf "%.8f" val , printf "x%.2f" w ]) hd in printTable lp header formatted $ False:repeat True -- | Convert a placement into a list of OpCodes (basically a job). iMoveToJob :: Node.List -- ^ The node list; only used for node -- names, so any version is good -- (before or after the operation) -> Instance.List -- ^ The instance list; also used for -- names only -> Idx -- ^ The index of the instance being -- moved -> IMove -- ^ The actual move to be described -> [OpCodes.OpCode] -- ^ The list of opcodes equivalent to -- the given move iMoveToJob nl il idx move = let inst = Container.find idx il iname = Instance.name inst lookNode n = case mkNonEmpty (Container.nameOf nl n) of -- FIXME: convert htools codebase to non-empty strings Bad msg -> error $ "Empty node name for idx " ++ show n ++ ": " ++ msg ++ "??" Ok ne -> Just ne opF = OpCodes.OpInstanceMigrate { OpCodes.opInstanceName = iname , OpCodes.opInstanceUuid = Nothing , OpCodes.opMigrationMode = Nothing -- default , OpCodes.opOldLiveMode = Nothing -- default as well , OpCodes.opTargetNode = Nothing -- this is drbd , OpCodes.opTargetNodeUuid = Nothing , OpCodes.opAllowRuntimeChanges = False , OpCodes.opIgnoreIpolicy = False , OpCodes.opMigrationCleanup = False , OpCodes.opIallocator = Nothing , OpCodes.opAllowFailover = True } opFA n = opF { OpCodes.opTargetNode = lookNode n } -- not drbd opR n = OpCodes.OpInstanceReplaceDisks { OpCodes.opInstanceName = iname , OpCodes.opInstanceUuid = Nothing , OpCodes.opEarlyRelease = False , OpCodes.opIgnoreIpolicy = False , OpCodes.opReplaceDisksMode = OpCodes.ReplaceNewSecondary , OpCodes.opReplaceDisksList = [] , OpCodes.opRemoteNode = lookNode n , OpCodes.opRemoteNodeUuid = Nothing , OpCodes.opIallocator = Nothing } in case move of Failover -> [ opF ] FailoverToAny np -> [ opFA np ] ReplacePrimary np -> [ opF, opR np, opF ] ReplaceSecondary ns -> [ opR ns ] ReplaceAndFailover np -> [ opR np, opF ] FailoverAndReplace ns -> [ opF, opR ns ] -- * Node group functions -- | Computes the group of an instance. instanceGroup :: Node.List -> Instance.Instance -> Result Gdx instanceGroup nl i = let sidx = Instance.sNode i pnode = Container.find (Instance.pNode i) nl snode = if sidx == Node.noSecondary then pnode else Container.find sidx nl pgroup = Node.group pnode sgroup = Node.group snode in if pgroup /= sgroup then fail ("Instance placed accross two node groups, primary " ++ show pgroup ++ ", secondary " ++ show sgroup) else return pgroup -- | Computes the group of an instance per the primary node. instancePriGroup :: Node.List -> Instance.Instance -> Gdx instancePriGroup nl i = let pnode = Container.find (Instance.pNode i) nl in Node.group pnode -- | Compute the list of badly allocated instances (split across node -- groups). findSplitInstances :: Node.List -> Instance.List -> [Instance.Instance] findSplitInstances nl = filter (not . isOk . instanceGroup nl) . Container.elems -- | Splits a cluster into the component node groups. splitCluster :: Node.List -> Instance.List -> [(Gdx, (Node.List, Instance.List))] splitCluster nl il = let ngroups = Node.computeGroups (Container.elems nl) in map (\(gdx, nodes) -> let nidxs = map Node.idx nodes nodes' = zip nidxs nodes instances = Container.filter ((`elem` nidxs) . Instance.pNode) il in (gdx, (Container.fromList nodes', instances))) ngroups -- | Compute the list of nodes that are to be evacuated, given a list -- of instances and an evacuation mode. nodesToEvacuate :: Instance.List -- ^ The cluster-wide instance list -> EvacMode -- ^ The evacuation mode we're using -> [Idx] -- ^ List of instance indices being evacuated -> IntSet.IntSet -- ^ Set of node indices nodesToEvacuate il mode = IntSet.delete Node.noSecondary . foldl' (\ns idx -> let i = Container.find idx il pdx = Instance.pNode i sdx = Instance.sNode i dt = Instance.diskTemplate i withSecondary = case dt of DTDrbd8 -> IntSet.insert sdx ns _ -> ns in case mode of ChangePrimary -> IntSet.insert pdx ns ChangeSecondary -> withSecondary ChangeAll -> IntSet.insert pdx withSecondary ) IntSet.empty
narurien/ganeti-ceph
src/Ganeti/HTools/Cluster.hs
Haskell
gpl-2.0
71,896
//----------------------------------------------------------------------------- // Class: CParaMeshXMLFile // Authors: LiXizhi // Emails: LiXizhi@yeah.net // Company: ParaEngine Corporation // Date: 2007.12.16 // Desc: //----------------------------------------------------------------------------- #include "ParaEngine.h" #include "FileManager.h" #include "BaseObject.h" #ifdef PARAENGINE_MOBILE #include <tinyxml2.h> #else #include <tinyxml.h> #include <xpath_processor.h> #endif #include "ParaMeshXMLFile.h" #include "memdebug.h" using namespace ParaEngine; /** @def larger than which mesh file can not be loaded. */ #define SUPPORTED_MESH_FILE_VERSION 0 CParaMeshXMLFile::CParaMeshXMLFile(void) { m_nType = TYPE_MESH_LOD; m_nPrimaryShader = TECH_SIMPLE_MESH_NORMAL; m_nVersion = 0; m_bHasBoundingBox = false; m_vMinPos = Vector3(0,0,0); m_vMaxPos = Vector3(0,0,0); } CParaMeshXMLFile::~CParaMeshXMLFile(void) { } bool ParaEngine::CParaMeshXMLFile::LoadFromFile( const string& filename ) { // auto set parent directory to be the parent directory of the input file. return LoadFromFile(filename, CParaFile::GetParentDirectoryFromPath(filename)); } bool ParaEngine::CParaMeshXMLFile::LoadFromFile(const string& filename, const string& parentDir) { CParaFile file(filename.c_str()); if(!file.isEof()) { SetParentDirectory(parentDir); // load return LoadFromBuffer(file.getBuffer(), (int)file.getSize()); } return false; } /** sample ParaEngine mesh xml file <mesh version=1 type=0> <boundingbox minx=0 miny=0 minz=0 maxx=1 maxy=1 maxz=1/> <shader index=3/> <submesh loddist=10 filename="LOD_10.x"/> <submesh loddist=50 filename="LOD_50.x"/> </mesh> */ bool ParaEngine::CParaMeshXMLFile::LoadFromBuffer(const char* pData, int nSize) { #ifdef PARAENGINE_MOBILE namespace TXML = tinyxml2; try { TXML::XMLDocument doc(true, TXML::COLLAPSE_WHITESPACE); doc.Parse(pData, nSize); TXML::XMLElement* pRoot = doc.RootElement(); if (pRoot) { pRoot->QueryIntAttribute("version", &m_nVersion); if (m_nVersion < SUPPORTED_MESH_FILE_VERSION) { OUTPUT_LOG("can not load para mesh xml file. because of a lower file version.\n"); } int nType = 0; pRoot->QueryIntAttribute("type", &nType); m_nType = (ParaMeshXMLType)nType; for (TXML::XMLNode* pChild = pRoot->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) { TXML::XMLElement* pElement = pChild->ToElement(); if (pElement) { std::string tagName = pElement->Name(); if (tagName == "boundingbox") { pElement->QueryFloatAttribute("minx", &m_vMinPos.x); pElement->QueryFloatAttribute("miny", &m_vMinPos.y); pElement->QueryFloatAttribute("minz", &m_vMinPos.z); pElement->QueryFloatAttribute("maxx", &m_vMaxPos.x); pElement->QueryFloatAttribute("maxy", &m_vMaxPos.y); pElement->QueryFloatAttribute("maxz", &m_vMaxPos.z); } else if (tagName == "shader") { pElement->QueryIntAttribute("index", &m_nPrimaryShader); // TODO: for shader parameters for (TXML::XMLNode* pSubChild = pElement->FirstChild(); pSubChild != 0; pSubChild = pSubChild->NextSibling()) { TXML::XMLElement* pParamElement = pSubChild->ToElement(); if (pParamElement) { std::string tagName = pParamElement->Name(); if (tagName == "params") { CParameter p; // param name p.SetName(pParamElement->Attribute("name", "")); p.SetTypeByString(pParamElement->Attribute("type", "")); p.SetValueByString(pParamElement->GetText()); m_paramBlock.AddParameter(p); } } } } else if (tagName == "submesh") { CSubMesh meshInfo; pElement->QueryFloatAttribute("loddist", &meshInfo.m_fToCameraDist); std::string filepath = pElement->Attribute("filename"); // check if it is relative path or absolute path if (filepath.find('/') != string::npos || filepath.find('\\') != string::npos) meshInfo.m_sFileName = filepath; else meshInfo.m_sFileName = m_sParentDirectory + filepath; m_SubMeshes.push_back(meshInfo); } } } } } catch (...) { OUTPUT_LOG("error parsing xml file %s**.xml \n", m_sParentDirectory.c_str()); return false; } return m_SubMeshes.size() > 0; #else TiXmlDocument doc; try { doc.Parse(pData, 0, TIXML_DEFAULT_ENCODING); TiXmlElement* pRoot = doc.RootElement(); if (pRoot != 0) { // get mesh file version TinyXPath::xpath_processor xpathProc(pRoot, "/mesh/@version"); TinyXPath::expression_result res = xpathProc.er_compute_xpath(); TinyXPath::node_set* pNodeSet = res.nsp_get_node_set(); if (pNodeSet != 0 && pNodeSet->u_get_nb_node_in_set() > 0) { const TiXmlAttribute* att = pNodeSet->XAp_get_attribute_in_set(0); m_nVersion = att->IntValue(); } if (m_nVersion < SUPPORTED_MESH_FILE_VERSION) { OUTPUT_LOG("can not load para mesh xml file. because of a lower file version.\n"); } { // get mesh type TinyXPath::xpath_processor xpathProc(pRoot, "/mesh/@type"); TinyXPath::expression_result res = xpathProc.er_compute_xpath(); TinyXPath::node_set* pNodeSet = res.nsp_get_node_set(); if (pNodeSet != 0 && pNodeSet->u_get_nb_node_in_set() > 0) { const TiXmlAttribute* att = pNodeSet->XAp_get_attribute_in_set(0); m_nType = (ParaMeshXMLType)att->IntValue(); } } { // get mesh bounding box TinyXPath::xpath_processor xpathProc(pRoot, "/mesh/boundingbox"); TinyXPath::expression_result res = xpathProc.er_compute_xpath(); TinyXPath::node_set* pNodeSet = res.nsp_get_node_set(); if (pNodeSet != 0 && pNodeSet->u_get_nb_node_in_set() > 0) { const TiXmlElement* pElem = pNodeSet->XNp_get_node_in_set(0)->ToElement(); // parse attributes const TiXmlAttribute* pAttr = pElem->FirstAttribute(); if (pAttr) { m_bHasBoundingBox = true; for (; pAttr; pAttr = pAttr->Next()) { string sName = pAttr->Name(); if (sName == "minx") { m_vMinPos.x = (float)(pAttr->DoubleValue()); } else if (sName == "miny") { m_vMinPos.y = (float)(pAttr->DoubleValue()); } else if (sName == "minz") { m_vMinPos.z = (float)(pAttr->DoubleValue()); } else if (sName == "maxx") { m_vMaxPos.x = (float)(pAttr->DoubleValue()); } else if (sName == "maxy") { m_vMaxPos.y = (float)(pAttr->DoubleValue()); } else if (sName == "maxz") { m_vMaxPos.z = (float)(pAttr->DoubleValue()); } } } } } { // get shader index. TinyXPath::xpath_processor xpathProc(pRoot, "/mesh/shader/@index"); TinyXPath::expression_result res = xpathProc.er_compute_xpath(); TinyXPath::node_set* pNodeSet = res.nsp_get_node_set(); if (pNodeSet != 0 && pNodeSet->u_get_nb_node_in_set() > 0) { const TiXmlAttribute* att = pNodeSet->XAp_get_attribute_in_set(0); m_nPrimaryShader = att->IntValue(); } } { // get shader parameters. TinyXPath::xpath_processor xpathProc(pRoot, "/mesh/shader/param"); TinyXPath::expression_result res = xpathProc.er_compute_xpath(); TinyXPath::node_set* pNodeSet = res.nsp_get_node_set(); if (pNodeSet != 0 && pNodeSet->u_get_nb_node_in_set() > 0) { int nCount = pNodeSet->u_get_nb_node_in_set(); for (int i = 0; i < nCount; ++i) { // for each parameter const TiXmlNode* node = pNodeSet->XNp_get_node_in_set(i); CParameter p; { // param name TinyXPath::xpath_processor xpathProc1(node->ToElement(), "@name"); TinyXPath::expression_result res1 = xpathProc1.er_compute_xpath(); TinyXPath::node_set* pNodeSet1 = res1.nsp_get_node_set(); if (pNodeSet1 != 0 && pNodeSet1->u_get_nb_node_in_set() > 0) { const TiXmlAttribute* att = pNodeSet1->XAp_get_attribute_in_set(0); p.SetName(att->Value()); } } { // get type TinyXPath::xpath_processor xpathProc1(node->ToElement(), "@type"); TinyXPath::expression_result res1 = xpathProc1.er_compute_xpath(); TinyXPath::node_set* pNodeSet1 = res1.nsp_get_node_set(); if (pNodeSet1 != 0 && pNodeSet1->u_get_nb_node_in_set() > 0) { const TiXmlAttribute* att = pNodeSet1->XAp_get_attribute_in_set(0); p.SetTypeByString(att->Value()); } } const TiXmlElement * pParamElement = node->ToElement(); if (pParamElement) { // get text value p.SetValueByString(pParamElement->GetText()); m_paramBlock.AddParameter(p); } } } } { // get mesh info. TinyXPath::xpath_processor xpathProc(pRoot, "/mesh/submesh"); TinyXPath::expression_result res = xpathProc.er_compute_xpath(); TinyXPath::node_set* pNodeSet = res.nsp_get_node_set(); if (pNodeSet != 0 && pNodeSet->u_get_nb_node_in_set() > 0) { int nCount = pNodeSet->u_get_nb_node_in_set(); m_SubMeshes.resize(nCount); for (int i = 0; i < nCount; ++i) { // for each sub meshes const TiXmlNode* node = pNodeSet->XNp_get_node_in_set(i); CSubMesh& meshInfo = m_SubMeshes[i]; { // LOD to camera distance TinyXPath::xpath_processor xpathProc1(node->ToElement(), "@loddist"); TinyXPath::expression_result res1 = xpathProc1.er_compute_xpath(); TinyXPath::node_set* pNodeSet1 = res1.nsp_get_node_set(); if (pNodeSet1 != 0 && pNodeSet1->u_get_nb_node_in_set() > 0) { const TiXmlAttribute* att = pNodeSet1->XAp_get_attribute_in_set(0); meshInfo.m_fToCameraDist = (float)(att->DoubleValue()); } } { // file name of the mesh TinyXPath::xpath_processor xpathProc1(node->ToElement(), "@filename"); TinyXPath::expression_result res1 = xpathProc1.er_compute_xpath(); TinyXPath::node_set* pNodeSet1 = res1.nsp_get_node_set(); if (pNodeSet1 != 0 && pNodeSet1->u_get_nb_node_in_set() > 0) { const TiXmlAttribute* att = pNodeSet1->XAp_get_attribute_in_set(0); string filepath = att->Value(); // check if it is relative path or absolute path if (filepath.find('/') != string::npos || filepath.find('\\') != string::npos) meshInfo.m_sFileName = filepath; else meshInfo.m_sFileName = m_sParentDirectory + filepath; } } } } } } else { OUTPUT_LOG("error parsing xml file %s**.xml \n", m_sParentDirectory.c_str()); } } catch (...) { OUTPUT_LOG("error parsing xml file %s**.xml \n", m_sParentDirectory.c_str()); } return m_SubMeshes.size() > 0; #endif } bool ParaEngine::CParaMeshXMLFile::SaveToFile( const string& filename ) { return false; }
LiXizhi/NPLRuntime
Client/trunk/ParaEngineClient/3dengine/ParaMeshXMLFile.cpp
C++
gpl-2.0
10,909
<!DOCTYPE html> <html lang="zh-Hans"> <head> <meta charset="utf-8"> <title>Category: 工具包 | 孔明灯</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <meta property="og:type" content="website"> <meta property="og:title" content="孔明灯"> <meta property="og:url" content="http://xiangxik.github.io/categories/工具包/index.html"> <meta property="og:site_name" content="孔明灯"> <meta name="twitter:card" content="summary"> <meta name="twitter:title" content="孔明灯"> <link rel="alternative" href="/atom.xml" title="孔明灯" type="application/atom+xml"> <link rel="icon" href="/favicon.ico"> <link href="//cdn.bootcss.com/animate.css/3.5.0/animate.min.css" rel="stylesheet"> <script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script> <link href="//cdn.bootcss.com/pace/1.0.2/themes/blue/pace-theme-minimal.css" rel="stylesheet"> <link rel="stylesheet" href="/css/style.css"> <link href="//cdn.bootcss.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="apple-touch-icon" href="/apple-touch-icon.png"> <link href="//cdn.bootcss.com/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet"> <script src="//cdn.bootcss.com/jquery/1.9.1/jquery.min.js"></script> <script src="//cdn.bootcss.com/clipboard.js/1.5.9/clipboard.min.js"></script> <script> var yiliaConfig = { fancybox: true, animate: true, isHome: false, isPost: false, isArchive: false, isTag: false, isCategory: true, open_in_new: false, fancybox_js: "//cdn.bootcss.com/fancybox/2.1.5/jquery.fancybox.min.js", scrollreveal: "//cdn.bootcss.com/scrollReveal.js/3.0.9/scrollreveal.min.js" } </script> <script> yiliaConfig.rootUrl = "/"; </script> <script> var _hmt = _hmt || []; (function() { var hm = document.createElement("script"); hm.src = "//hm.baidu.com/hm.js?24545fe3f0abae1186c593477187998d"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(hm, s); })(); </script> </head> <body> <div id="container"> <div class="left-col"> <div class="overlay"></div> <div class="intrude-less"> <header id="header" class="inner"> <a href="/" class="profilepic"> <img src="/img/avatar.jpg" class="animated zoomIn"> </a> <hgroup> <h1 class="header-author"><a href="/">孔明灯</a></h1> </hgroup> <p class="header-subtitle">照亮前方,照亮自己。</p> <div id="switch-btn" class="switch-btn"> <div class="icon"> <div class="icon-ctn"> <div class="icon-wrap icon-house" data-idx="0"> <div class="birdhouse"></div> <div class="birdhouse_holes"></div> </div> <div class="icon-wrap icon-ribbon hide" data-idx="1"> <div class="ribbon"></div> </div> <div class="icon-wrap icon-link hide" data-idx="2"> <div class="loopback_l"></div> <div class="loopback_r"></div> </div> <div class="icon-wrap icon-me hide" data-idx="3"> <div class="user"></div> <div class="shoulder"></div> </div> </div> </div> <div class="tips-box hide"> <div class="tips-arrow"></div> <ul class="tips-inner"> <li>菜单</li> <li>标签</li> <li>友情链接</li> <li>关于我</li> </ul> </div> </div> <div id="switch-area" class="switch-area"> <div class="switch-wrap"> <section class="switch-part switch-part1"> <nav class="header-menu"> <ul> <li><a href="/">主页</a></li> <li><a href="/archives/">所有文章</a></li> <li><a href="/tags/">标签云</a></li> <li><a href="/about/">关于我</a></li> </ul> </nav> <nav class="header-nav"> <ul class="social"> <a class="fa Email" target="_blank" href="mailto:ken@whenling.com" title="Email"></a> <a class="fa GitHub" target="_blank" href="http://github.com/xiangxik" title="GitHub"></a> <a class="fa RSS" target="_blank" href="/atom.xml" title="RSS"></a> <a class="fa 知乎" target="_blank" href="http://zhihu.com/people/kongxiangxi" title="知乎"></a> <a class="fa QQ" target="_blank" href="http://wpa.qq.com/msgrd?v=3&uin=156801554&site=qq&menu=yes" title="QQ"></a> <a class="fa 微信" target="_blank" href="/kongstream" title="微信"></a> </ul> </nav> </section> <section class="switch-part switch-part2"> <div class="widget tagcloud" id="js-tagcloud"> <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/java/">java</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/linux/">linux</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/nosql/">nosql</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/关系数据库/">关系数据库</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/吉他谱/">吉他谱</a></li></ul> </div> </section> <section class="switch-part switch-part3"> <div id="js-friends"> <a target="_blank" class="main-nav-link switch-friends-link" href="http://www.whenling.com">当凌科技官网</a> <a target="_blank" class="main-nav-link switch-friends-link" href="http://fullstack.whenling.com">全栈程序员论坛</a> <a target="_blank" class="main-nav-link switch-friends-link" href="http://www.iplucky.com">鸬鹚网</a> <a target="_blank" class="main-nav-link switch-friends-link" href="http://www.yisongshui.com">易送水</a> </div> </section> <section class="switch-part switch-part4"> <div id="js-aboutme">全栈工程师</div> </section> </div> </div> </header> </div> </div> <div class="mid-col"> <nav id="mobile-nav"> <div class="overlay"> <div class="slider-trigger"></div> <h1 class="header-author js-mobile-header hide"><a href="/" title="回到主页">孔明灯</a></h1> </div> <div class="intrude-less"> <header id="header" class="inner"> <a href="/" class="profilepic"> <img src="/img/avatar.jpg" class="animated zoomIn"> </a> <hgroup> <h1 class="header-author"><a href="/" title="回到主页">孔明灯</a></h1> </hgroup> <p class="header-subtitle">照亮前方,照亮自己。</p> <nav class="header-menu"> <ul> <li><a href="/">主页</a></li> <li><a href="/archives/">所有文章</a></li> <li><a href="/tags/">标签云</a></li> <li><a href="/about/">关于我</a></li> <div class="clearfix"></div> </ul> </nav> <nav class="header-nav"> <ul class="social"> <a class="fa Email" target="_blank" href="mailto:ken@whenling.com" title="Email"></a> <a class="fa GitHub" target="_blank" href="http://github.com/xiangxik" title="GitHub"></a> <a class="fa RSS" target="_blank" href="/atom.xml" title="RSS"></a> <a class="fa 知乎" target="_blank" href="http://zhihu.com/people/kongxiangxi" title="知乎"></a> <a class="fa QQ" target="_blank" href="http://wpa.qq.com/msgrd?v=3&uin=156801554&site=qq&menu=yes" title="QQ"></a> <a class="fa 微信" target="_blank" href="/kongstream" title="微信"></a> </ul> </nav> </header> </div> <link class="menu-list" tags="标签" friends="友情链接" about="关于我"/> </nav> <div class="body-wrap"> <section class="archives-wrap"> <div class="archive-year-wrap"> <a href="/archives/2016" class="archive-year">2016</a> </div> <div class="archives"> <article class="archive-article archive-type-post"> <div class="archive-article-inner"> <header class="archive-article-header"> <div class="article-meta"> <a href="/2016/08/29/socket_flow/" class="archive-article-date"> <time datetime="2016-08-29T09:25:49.000Z" itemprop="datePublished">08-29</time> </a> </div> <h1 itemprop="name"> <a class="archive-article-title" href="/2016/08/29/socket_flow/">流式WebSocket</a> </h1> <div class="article-info info-on-archive"> <div class="article-category tagcloud"> <a class="article-category-link" href="/categories/工具包/">工具包</a> </div> <div class="article-tag tagcloud"> <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/java/">java</a></li></ul> </div> </div> <div class="clearfix"></div> </header> </div> </article> <article class="archive-article archive-type-post"> <div class="archive-article-inner"> <header class="archive-article-header"> <div class="article-meta"> <a href="/2016/05/08/infinispan/" class="archive-article-date"> <time datetime="2016-05-08T03:43:13.000Z" itemprop="datePublished">05-08</time> </a> </div> <h1 itemprop="name"> <a class="archive-article-title" href="/2016/05/08/infinispan/">Infinispan缓存</a> </h1> <div class="article-info info-on-archive"> <div class="article-category tagcloud"> <a class="article-category-link" href="/categories/工具包/">工具包</a> </div> <div class="article-tag tagcloud"> <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/java/">java</a></li></ul> </div> </div> <div class="clearfix"></div> </header> </div> </article> <article class="archive-article archive-type-post"> <div class="archive-article-inner"> <header class="archive-article-header"> <div class="article-meta"> <a href="/2016/05/01/apache_configuration/" class="archive-article-date"> <time datetime="2016-05-01T04:23:42.000Z" itemprop="datePublished">05-01</time> </a> </div> <h1 itemprop="name"> <a class="archive-article-title" href="/2016/05/01/apache_configuration/">Apache Configuration 详解</a> </h1> <div class="article-info info-on-archive"> <div class="article-category tagcloud"> <a class="article-category-link" href="/categories/工具包/">工具包</a> </div> <div class="article-tag tagcloud"> <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/java/">java</a></li></ul> </div> </div> <div class="clearfix"></div> </header> </div> </article> <article class="archive-article archive-type-post"> <div class="archive-article-inner"> <header class="archive-article-header"> <div class="article-meta"> <a href="/2016/03/05/groovy_template/" class="archive-article-date"> <time datetime="2016-03-05T02:25:29.000Z" itemprop="datePublished">03-05</time> </a> </div> <h1 itemprop="name"> <a class="archive-article-title" href="/2016/03/05/groovy_template/">Groovy Template 详解</a> </h1> <div class="article-info info-on-archive"> <div class="article-category tagcloud"> <a class="article-category-link" href="/categories/工具包/">工具包</a> </div> <div class="article-tag tagcloud"> <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/java/">java</a></li></ul> </div> </div> <div class="clearfix"></div> </header> </div> </article> <article class="archive-article archive-type-post"> <div class="archive-article-inner"> <header class="archive-article-header"> <div class="article-meta"> <a href="/2016/02/29/spring_data/" class="archive-article-date"> <time datetime="2016-02-29T09:25:49.000Z" itemprop="datePublished">02-29</time> </a> </div> <h1 itemprop="name"> <a class="archive-article-title" href="/2016/02/29/spring_data/">Spring Data 详解</a> </h1> <div class="article-info info-on-archive"> <div class="article-category tagcloud"> <a class="article-category-link" href="/categories/工具包/">工具包</a> </div> <div class="article-tag tagcloud"> <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/java/">java</a></li></ul> </div> </div> <div class="clearfix"></div> </header> </div> </article> </div></section> </div> <footer id="footer"> <div class="outer"> <div id="footer-info"> <div class="footer-left"> <i class="fa fa-copyright"></i> 2016 孔明灯 </div> <div class="footer-right"> <a href="http://www.whenling.com" target="_blank" title="广州当凌信息科技有限公司">当凌科技</a> </div> </div> <div class="visit"> <span id="busuanzi_container_site_pv" style='display:none'> <span id="site-visit" >本站到访数: <span id="busuanzi_value_site_uv"></span> </span> </span> <span>, </span> <span id="busuanzi_container_page_pv" style='display:none'> <span id="page-visit">本页阅读量: <span id="busuanzi_value_page_pv"></span> </span> </span> </div> </div> </footer> </div> <script src="/js/GithubRepoWidget.js"></script> <script data-main="/js/main.js" src="//cdn.bootcss.com/require.js/2.1.22/require.min.js"></script> <script> $(document).ready(function() { var iPad = window.navigator.userAgent.indexOf('iPad'); if (iPad > -1 || $(".left-col").css("display") === "none") { var bgColorList = ["#9db3f4", "#414141", "#e5a859", "#f5dfc6", "#c084a0", "#847e72", "#cd8390", "#996731"]; var bgColor = Math.ceil(Math.random() * (bgColorList.length - 1)); $("body").css({"background-color": bgColorList[bgColor], "background-size": "cover"}); } else { var backgroundnum = 5; var backgroundimg = "url(/background/bg-x.jpg)".replace(/x/gi, Math.ceil(Math.random() * backgroundnum)); $("body").css({"background": backgroundimg, "background-attachment": "fixed", "background-size": "cover"}); } }) </script> <div class="scroll" id="scroll"> <a href="#" title="返回顶部"><i class="fa fa-arrow-up"></i></a> <a href="#comments" title="查看评论"><i class="fa fa-comments-o"></i></a> <a href="#footer" title="转到底部"><i class="fa fa-arrow-down"></i></a> </div> <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"> </script> </div> </body> </html>
xiangxik/xiangxik.github.io
categories/工具包/index.html
HTML
gpl-2.0
18,422
package eu.maydu.gwt.validation.client.i18n; public class StandardValidationMessagesImpl_en implements eu.maydu.gwt.validation.client.i18n.StandardValidationMessagesImpl { public java.lang.String validator_assertFalse() { return "Assertion failed"; } public java.lang.String validator_pattern() { return "Incorrect pattern"; } public java.lang.String validator_ean() { return "Invalid EAN"; } public java.lang.String validator_creditCard() { return "Invalid credit card number"; } public java.lang.String min(int minValue,int actualValue) { return "Minimum value for this field is '" + minValue + "'. You entered '" + actualValue + "'"; } public java.lang.String max(double maxValue,double actualValue) { return "Maximum value for this field is '" + maxValue + "'. You entered '" + actualValue + "'"; } public java.lang.String regexNotFulfilled() { return "The text does not fulfill the given regular expression"; } public java.lang.String length(int minLength,int maxLength,int actualLength) { return "Needs a length between '" + minLength + "' and '" + maxLength + "'. Was '" + actualLength + "'"; } public java.lang.String validator_notNull() { return "Must be given"; } public java.lang.String notInRange(double min,double max,double value) { return "Value '" + value + "' lies beyond the boundaries [" + min + "," + max + "]"; } public java.lang.String validator_range() { return "Not in range"; } public java.lang.String max(int maxValue,int actualValue) { return "Maximum value for this field is '" + maxValue + "'. You entered '" + actualValue + "'"; } public java.lang.String notADouble() { return "Not a floating point number"; } public java.lang.String notALong() { return "Not a whole number"; } public java.lang.String notEqual() { return "Should not be equal"; } public java.lang.String validator_assertTrue() { return "Assertion failed"; } public java.lang.String mustSelectValue() { return "Please select a value"; } public java.lang.String equal() { return "Should be equal"; } public java.lang.String unparsableDate() { return "Wrong date format"; } public java.lang.String notARegEx() { return "No valid regular expression given"; } public java.lang.String notNull() { return "Must be given"; } public java.lang.String validator_future() { return "Must be a future date"; } public java.lang.String isNull() { return "Should not be given"; } public java.lang.String notInRange(float min,float max,float value) { return "Value '" + value + "' lies beyond the boundaries [" + min + "," + max + "]"; } public java.lang.String notAValidTimeWithSecondsRequired(java.lang.String parameter) { return "'" + parameter + "' is not a valid time (seconds must be given)"; } public java.lang.String min(float minValue,float actualValue) { return "Minimum value for this field is '" + minValue + "'. You entered '" + actualValue + "'"; } public java.lang.String validator_size() { return "Incorrect number of elements"; } public java.lang.String validator_past() { return "Must be a past date"; } public java.lang.String validator_email() { return "Not a well-formed email address"; } public java.lang.String notAValidEmail(java.lang.String givenEmailInput) { return "'" + givenEmailInput + "' is not a valid email address"; } public java.lang.String notAFloat() { return "Not a floating point number"; } public java.lang.String stringsNotEqual() { return "Strings must be equal"; } public java.lang.String notInRange(int min,int max,int value) { return "Value '" + value + "' lies beyond the boundaries [" + min + "," + max + "]"; } public java.lang.String notAValidCharacter(char c) { return "Not a valid character: '" + c + "'"; } public java.lang.String validator_max() { return "Too big"; } public java.lang.String validator_notEmpty() { return "May not be null or empty"; } public java.lang.String max(long maxValue,long actualValue) { return "Maximum value for this field is '" + maxValue + "'. You entered '" + actualValue + "'"; } public java.lang.String notAnInteger() { return "Not a whole number"; } public java.lang.String validator_min() { return "Too small"; } public java.lang.String validator_length() { return "Length not correct"; } public java.lang.String notInRange(long min,long max,long value) { return "Value '" + value + "' lies beyond the boundaries [" + min + "," + max + "]"; } public java.lang.String notEmpty() { return "Mustn't be empty"; } public java.lang.String min(long minValue,long actualValue) { return "Minimum value for this field is '" + minValue + "'. You entered '" + actualValue + "'"; } public java.lang.String noDateGiven() { return "No date entered"; } public java.lang.String notAValidTimeWithoutSeconds(java.lang.String parameter) { return "'" + parameter + "' is not a valid time (seconds must not be given)"; } public java.lang.String max(float maxValue,float actualValue) { return "Maximum value for this field is '" + maxValue + "'. You entered '" + actualValue + "'"; } public java.lang.String validator_digits() { return "Numeric value out of bounds"; } public java.lang.String notAValidTimeWithSecondsOptionally(java.lang.String parameter) { return "'" + parameter + "' is not a valid time (seconds may be given)"; } public java.lang.String min(double minValue,double actualValue) { return "Minimum value for this field is '" + minValue + "'. You entered '" + actualValue + "'"; } }
midaboghetich/netnumero
gen/eu/maydu/gwt/validation/client/i18n/StandardValidationMessagesImpl_en.java
Java
gpl-2.0
5,885
/* This file was generated by SableCC (http://www.sablecc.org/). */ package se.sics.kola.node; public abstract class PElementValue extends Node { // Empty body }
kompics/kola
src/main/java/se/sics/kola/node/PElementValue.java
Java
gpl-2.0
168
/* * drivers/cpufreq/cpufreq_interactive.c * * Copyright (C) 2010 Google, Inc. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * 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. * * Author: Mike Chan (mike@android.com) * */ /* * NOTE: This file has been modified by Sony Mobile Communications Inc. * Modifications are Copyright (c) 2015 Sony Mobile Communications Inc, * and licensed under the license of the file. */ #include <linux/cpu.h> #include <linux/cpumask.h> #include <linux/cpufreq.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/rwsem.h> #include <linux/sched.h> #include <linux/sched/rt.h> #include <linux/tick.h> #include <linux/time.h> #include <linux/timer.h> #include <linux/workqueue.h> #include <linux/kthread.h> #include <linux/slab.h> #include <linux/kernel_stat.h> #include <asm/cputime.h> #define CREATE_TRACE_POINTS #include <trace/events/cpufreq_interactive.h> struct cpufreq_interactive_cpuinfo { struct timer_list cpu_timer; struct timer_list cpu_slack_timer; spinlock_t load_lock; /* protects the next 4 fields */ u64 time_in_idle; u64 time_in_idle_timestamp; u64 cputime_speedadj; u64 cputime_speedadj_timestamp; u64 last_evaluated_jiffy; struct cpufreq_policy *policy; struct cpufreq_frequency_table *freq_table; spinlock_t target_freq_lock; /*protects target freq */ unsigned int target_freq; unsigned int floor_freq; unsigned int max_freq; unsigned int min_freq; u64 floor_validate_time; u64 local_fvtime; /* per-cpu floor_validate_time */ u64 hispeed_validate_time; /* cluster hispeed_validate_time */ u64 local_hvtime; /* per-cpu hispeed_validate_time */ u64 max_freq_hyst_start_time; struct rw_semaphore enable_sem; bool reject_notification; int governor_enabled; struct cpufreq_interactive_tunables *cached_tunables; int first_cpu; }; static DEFINE_PER_CPU(struct cpufreq_interactive_cpuinfo, cpuinfo); /* realtime thread handles frequency scaling */ static struct task_struct *speedchange_task; static cpumask_t speedchange_cpumask; static spinlock_t speedchange_cpumask_lock; static struct mutex gov_lock; static int set_window_count; static int migration_register_count; static struct mutex sched_lock; /* Target load. Lower values result in higher CPU speeds. */ #define DEFAULT_TARGET_LOAD 90 static unsigned int default_target_loads[] = {DEFAULT_TARGET_LOAD}; #define DEFAULT_TIMER_RATE (20 * USEC_PER_MSEC) #define DEFAULT_ABOVE_HISPEED_DELAY DEFAULT_TIMER_RATE static unsigned int default_above_hispeed_delay[] = { DEFAULT_ABOVE_HISPEED_DELAY }; struct cpufreq_interactive_tunables { int usage_count; /* Hi speed to bump to from lo speed when load burst (default max) */ unsigned int hispeed_freq; /* Go to hi speed when CPU load at or above this value. */ #define DEFAULT_GO_HISPEED_LOAD 99 unsigned long go_hispeed_load; /* Target load. Lower values result in higher CPU speeds. */ spinlock_t target_loads_lock; unsigned int *target_loads; int ntarget_loads; /* * The minimum amount of time to spend at a frequency before we can ramp * down. */ #define DEFAULT_MIN_SAMPLE_TIME (80 * USEC_PER_MSEC) unsigned long min_sample_time; /* * The sample rate of the timer used to increase frequency */ unsigned long timer_rate; /* * Wait this long before raising speed above hispeed, by default a * single timer interval. */ spinlock_t above_hispeed_delay_lock; unsigned int *above_hispeed_delay; int nabove_hispeed_delay; /* Non-zero means indefinite speed boost active */ int boost_val; /* Duration of a boot pulse in usecs */ int boostpulse_duration_val; /* End time of boost pulse in ktime converted to usecs */ u64 boostpulse_endtime; bool boosted; /* * Max additional time to wait in idle, beyond timer_rate, at speeds * above minimum before wakeup to reduce speed, or -1 if unnecessary. */ #define DEFAULT_TIMER_SLACK (4 * DEFAULT_TIMER_RATE) int timer_slack_val; bool io_is_busy; /* scheduler input related flags */ bool use_sched_load; bool use_migration_notif; /* * Whether to align timer windows across all CPUs. When * use_sched_load is true, this flag is ignored and windows * will always be aligned. */ bool align_windows; /* * Stay at max freq for at least max_freq_hysteresis before dropping * frequency. */ unsigned int max_freq_hysteresis; }; /* For cases where we have single governor instance for system */ static struct cpufreq_interactive_tunables *common_tunables; static struct attribute_group *get_sysfs_attr(void); /* Round to starting jiffy of next evaluation window */ static u64 round_to_nw_start(u64 jif, struct cpufreq_interactive_tunables *tunables) { unsigned long step = usecs_to_jiffies(tunables->timer_rate); u64 ret; if (tunables->use_sched_load || tunables->align_windows) { do_div(jif, step); ret = (jif + 1) * step; } else { ret = jiffies + usecs_to_jiffies(tunables->timer_rate); } return ret; } static inline int set_window_helper( struct cpufreq_interactive_tunables *tunables) { return sched_set_window(round_to_nw_start(get_jiffies_64(), tunables), usecs_to_jiffies(tunables->timer_rate)); } static void cpufreq_interactive_timer_resched(unsigned long cpu, bool slack_only) { struct cpufreq_interactive_cpuinfo *pcpu = &per_cpu(cpuinfo, cpu); struct cpufreq_interactive_tunables *tunables = pcpu->policy->governor_data; u64 expires; unsigned long flags; spin_lock_irqsave(&pcpu->load_lock, flags); expires = round_to_nw_start(pcpu->last_evaluated_jiffy, tunables); if (!slack_only) { pcpu->time_in_idle = get_cpu_idle_time(smp_processor_id(), &pcpu->time_in_idle_timestamp, tunables->io_is_busy); pcpu->cputime_speedadj = 0; pcpu->cputime_speedadj_timestamp = pcpu->time_in_idle_timestamp; del_timer(&pcpu->cpu_timer); pcpu->cpu_timer.expires = expires; add_timer_on(&pcpu->cpu_timer, cpu); } if (tunables->timer_slack_val >= 0 && pcpu->target_freq > pcpu->policy->min) { expires += usecs_to_jiffies(tunables->timer_slack_val); del_timer(&pcpu->cpu_slack_timer); pcpu->cpu_slack_timer.expires = expires; add_timer_on(&pcpu->cpu_slack_timer, cpu); } spin_unlock_irqrestore(&pcpu->load_lock, flags); } /* The caller shall take enable_sem write semaphore to avoid any timer race. * The cpu_timer and cpu_slack_timer must be deactivated when calling this * function. */ static void cpufreq_interactive_timer_start( struct cpufreq_interactive_tunables *tunables, int cpu) { struct cpufreq_interactive_cpuinfo *pcpu = &per_cpu(cpuinfo, cpu); u64 expires = round_to_nw_start(pcpu->last_evaluated_jiffy, tunables); unsigned long flags; spin_lock_irqsave(&pcpu->load_lock, flags); pcpu->cpu_timer.expires = expires; add_timer_on(&pcpu->cpu_timer, cpu); if (tunables->timer_slack_val >= 0 && pcpu->target_freq > pcpu->policy->min) { expires += usecs_to_jiffies(tunables->timer_slack_val); pcpu->cpu_slack_timer.expires = expires; add_timer_on(&pcpu->cpu_slack_timer, cpu); } pcpu->time_in_idle = get_cpu_idle_time(cpu, &pcpu->time_in_idle_timestamp, tunables->io_is_busy); pcpu->cputime_speedadj = 0; pcpu->cputime_speedadj_timestamp = pcpu->time_in_idle_timestamp; spin_unlock_irqrestore(&pcpu->load_lock, flags); } static unsigned int freq_to_above_hispeed_delay( struct cpufreq_interactive_tunables *tunables, unsigned int freq) { int i; unsigned int ret; unsigned long flags; spin_lock_irqsave(&tunables->above_hispeed_delay_lock, flags); for (i = 0; i < tunables->nabove_hispeed_delay - 1 && freq >= tunables->above_hispeed_delay[i+1]; i += 2) ; ret = tunables->above_hispeed_delay[i]; spin_unlock_irqrestore(&tunables->above_hispeed_delay_lock, flags); return ret; } static unsigned int freq_to_targetload( struct cpufreq_interactive_tunables *tunables, unsigned int freq) { int i; unsigned int ret; unsigned long flags; spin_lock_irqsave(&tunables->target_loads_lock, flags); for (i = 0; i < tunables->ntarget_loads - 1 && freq >= tunables->target_loads[i+1]; i += 2) ; ret = tunables->target_loads[i]; spin_unlock_irqrestore(&tunables->target_loads_lock, flags); return ret; } /* * If increasing frequencies never map to a lower target load then * choose_freq() will find the minimum frequency that does not exceed its * target load given the current load. */ static unsigned int choose_freq(struct cpufreq_interactive_cpuinfo *pcpu, unsigned int loadadjfreq) { unsigned int freq = pcpu->policy->cur; unsigned int prevfreq, freqmin, freqmax; unsigned int tl; int index; freqmin = 0; freqmax = UINT_MAX; do { prevfreq = freq; tl = freq_to_targetload(pcpu->policy->governor_data, freq); /* * Find the lowest frequency where the computed load is less * than or equal to the target load. */ if (cpufreq_frequency_table_target( pcpu->policy, pcpu->freq_table, loadadjfreq / tl, CPUFREQ_RELATION_L, &index)) break; freq = pcpu->freq_table[index].frequency; if (freq > prevfreq) { /* The previous frequency is too low. */ freqmin = prevfreq; if (freq >= freqmax) { /* * Find the highest frequency that is less * than freqmax. */ if (cpufreq_frequency_table_target( pcpu->policy, pcpu->freq_table, freqmax - 1, CPUFREQ_RELATION_H, &index)) break; freq = pcpu->freq_table[index].frequency; if (freq == freqmin) { /* * The first frequency below freqmax * has already been found to be too * low. freqmax is the lowest speed * we found that is fast enough. */ freq = freqmax; break; } } } else if (freq < prevfreq) { /* The previous frequency is high enough. */ freqmax = prevfreq; if (freq <= freqmin) { /* * Find the lowest frequency that is higher * than freqmin. */ if (cpufreq_frequency_table_target( pcpu->policy, pcpu->freq_table, freqmin + 1, CPUFREQ_RELATION_L, &index)) break; freq = pcpu->freq_table[index].frequency; /* * If freqmax is the first frequency above * freqmin then we have already found that * this speed is fast enough. */ if (freq == freqmax) break; } } /* If same frequency chosen as previous then done. */ } while (freq != prevfreq); return freq; } static u64 update_load(int cpu) { struct cpufreq_interactive_cpuinfo *pcpu = &per_cpu(cpuinfo, cpu); struct cpufreq_interactive_tunables *tunables = pcpu->policy->governor_data; u64 now; u64 now_idle; unsigned int delta_idle; unsigned int delta_time; u64 active_time; now_idle = get_cpu_idle_time(cpu, &now, tunables->io_is_busy); delta_idle = (unsigned int)(now_idle - pcpu->time_in_idle); delta_time = (unsigned int)(now - pcpu->time_in_idle_timestamp); if (delta_time <= delta_idle) active_time = 0; else active_time = delta_time - delta_idle; pcpu->cputime_speedadj += active_time * pcpu->policy->cur; pcpu->time_in_idle = now_idle; pcpu->time_in_idle_timestamp = now; return now; } static int max_local_load = 100; module_param(max_local_load, int, 0644); static void cpufreq_interactive_timer(unsigned long data) { u64 now; unsigned int delta_time; u64 cputime_speedadj; int cpu_load; struct cpufreq_interactive_cpuinfo *pcpu = &per_cpu(cpuinfo, data); struct cpufreq_interactive_tunables *tunables = pcpu->policy->governor_data; unsigned int new_freq; unsigned int loadadjfreq; unsigned int index; unsigned long flags; struct cpufreq_govinfo int_info; u64 max_fvtime; if (!down_read_trylock(&pcpu->enable_sem)) return; if (!pcpu->governor_enabled) goto exit; spin_lock_irqsave(&pcpu->load_lock, flags); pcpu->last_evaluated_jiffy = get_jiffies_64(); now = update_load(data); if (tunables->use_sched_load) { /* * Unlock early to avoid deadlock. * * load_change_callback() for thread migration already * holds rq lock. Then it locks load_lock to avoid racing * with cpufreq_interactive_timer_resched/start(). * sched_get_busy() will also acquire rq lock. Thus we * can't hold load_lock when calling sched_get_busy(). * * load_lock used in this function protects time * and load information. These stats are not used when * scheduler input is available. Thus unlocking load_lock * early is perfectly OK. */ spin_unlock_irqrestore(&pcpu->load_lock, flags); cputime_speedadj = (u64)sched_get_busy(data) * pcpu->policy->cpuinfo.max_freq; do_div(cputime_speedadj, tunables->timer_rate); } else { delta_time = (unsigned int) (now - pcpu->cputime_speedadj_timestamp); cputime_speedadj = pcpu->cputime_speedadj; spin_unlock_irqrestore(&pcpu->load_lock, flags); if (WARN_ON_ONCE(!delta_time)) goto rearm; do_div(cputime_speedadj, delta_time); } loadadjfreq = (unsigned int)cputime_speedadj * 100; int_info.cpu = data; int_info.load = loadadjfreq / pcpu->policy->max; int_info.sampling_rate_us = tunables->timer_rate; atomic_notifier_call_chain(&cpufreq_govinfo_notifier_list, CPUFREQ_LOAD_CHANGE, &int_info); spin_lock_irqsave(&pcpu->target_freq_lock, flags); cpu_load = loadadjfreq / pcpu->policy->cur; tunables->boosted = tunables->boost_val || now < tunables->boostpulse_endtime; if (cpu_load >= tunables->go_hispeed_load || tunables->boosted) { if (pcpu->policy->cur < tunables->hispeed_freq && cpu_load <= max_local_load) { new_freq = tunables->hispeed_freq; } else { new_freq = choose_freq(pcpu, loadadjfreq); if (new_freq < tunables->hispeed_freq) new_freq = tunables->hispeed_freq; } } else { new_freq = choose_freq(pcpu, loadadjfreq); } if (cpu_load <= max_local_load && pcpu->policy->cur >= tunables->hispeed_freq && new_freq > pcpu->policy->cur && now - pcpu->hispeed_validate_time < freq_to_above_hispeed_delay(tunables, pcpu->policy->cur)) { trace_cpufreq_interactive_notyet( data, cpu_load, pcpu->target_freq, pcpu->policy->cur, new_freq); spin_unlock_irqrestore(&pcpu->target_freq_lock, flags); goto rearm; } pcpu->local_hvtime = now; if (cpufreq_frequency_table_target(pcpu->policy, pcpu->freq_table, new_freq, CPUFREQ_RELATION_L, &index)) { spin_unlock_irqrestore(&pcpu->target_freq_lock, flags); goto rearm; } new_freq = pcpu->freq_table[index].frequency; if (new_freq < pcpu->target_freq && now - pcpu->max_freq_hyst_start_time < tunables->max_freq_hysteresis) { trace_cpufreq_interactive_notyet(data, cpu_load, pcpu->target_freq, pcpu->policy->cur, new_freq); spin_unlock_irqrestore(&pcpu->target_freq_lock, flags); goto rearm; } /* * Do not scale below floor_freq unless we have been at or above the * floor frequency for the minimum sample time since last validated. */ max_fvtime = max(pcpu->floor_validate_time, pcpu->local_fvtime); if (new_freq < pcpu->floor_freq && pcpu->target_freq >= pcpu->policy->cur) { if (now - max_fvtime < tunables->min_sample_time) { trace_cpufreq_interactive_notyet( data, cpu_load, pcpu->target_freq, pcpu->policy->cur, new_freq); spin_unlock_irqrestore(&pcpu->target_freq_lock, flags); goto rearm; } } /* * Update the timestamp for checking whether speed has been held at * or above the selected frequency for a minimum of min_sample_time, * if not boosted to hispeed_freq. If boosted to hispeed_freq then we * allow the speed to drop as soon as the boostpulse duration expires * (or the indefinite boost is turned off). */ if (!tunables->boosted || new_freq > tunables->hispeed_freq) { pcpu->floor_freq = new_freq; if (pcpu->target_freq >= pcpu->policy->cur || new_freq >= pcpu->policy->cur) pcpu->local_fvtime = now; } if (new_freq == pcpu->policy->max) pcpu->max_freq_hyst_start_time = now; if (pcpu->target_freq == new_freq) { trace_cpufreq_interactive_already( data, cpu_load, pcpu->target_freq, pcpu->policy->cur, new_freq); spin_unlock_irqrestore(&pcpu->target_freq_lock, flags); goto rearm; } trace_cpufreq_interactive_target(data, cpu_load, pcpu->target_freq, pcpu->policy->cur, new_freq); pcpu->target_freq = new_freq; spin_unlock_irqrestore(&pcpu->target_freq_lock, flags); spin_lock_irqsave(&speedchange_cpumask_lock, flags); cpumask_set_cpu(data, &speedchange_cpumask); spin_unlock_irqrestore(&speedchange_cpumask_lock, flags); wake_up_process(speedchange_task); rearm: if (!timer_pending(&pcpu->cpu_timer)) cpufreq_interactive_timer_resched(data, false); exit: up_read(&pcpu->enable_sem); return; } static void cpufreq_interactive_idle_end(void) { struct cpufreq_interactive_cpuinfo *pcpu = &per_cpu(cpuinfo, smp_processor_id()); if (!down_read_trylock(&pcpu->enable_sem)) return; if (!pcpu->governor_enabled) { up_read(&pcpu->enable_sem); return; } /* Arm the timer for 1-2 ticks later if not already. */ if (!timer_pending(&pcpu->cpu_timer)) { cpufreq_interactive_timer_resched(smp_processor_id(), false); } else if (time_after_eq(jiffies, pcpu->cpu_timer.expires)) { del_timer(&pcpu->cpu_timer); del_timer(&pcpu->cpu_slack_timer); cpufreq_interactive_timer(smp_processor_id()); } up_read(&pcpu->enable_sem); } static int cpufreq_interactive_speedchange_task(void *data) { unsigned int cpu; cpumask_t tmp_mask; unsigned long flags; struct cpufreq_interactive_cpuinfo *pcpu; while (1) { set_current_state(TASK_INTERRUPTIBLE); spin_lock_irqsave(&speedchange_cpumask_lock, flags); if (cpumask_empty(&speedchange_cpumask)) { spin_unlock_irqrestore(&speedchange_cpumask_lock, flags); schedule(); if (kthread_should_stop()) break; spin_lock_irqsave(&speedchange_cpumask_lock, flags); } set_current_state(TASK_RUNNING); tmp_mask = speedchange_cpumask; cpumask_clear(&speedchange_cpumask); spin_unlock_irqrestore(&speedchange_cpumask_lock, flags); for_each_cpu(cpu, &tmp_mask) { unsigned int j; unsigned int max_freq = 0; struct cpufreq_interactive_cpuinfo *pjcpu; u64 hvt = ~0ULL, fvt = 0; pcpu = &per_cpu(cpuinfo, cpu); if (!down_read_trylock(&pcpu->enable_sem)) continue; if (!pcpu->governor_enabled) { up_read(&pcpu->enable_sem); continue; } for_each_cpu(j, pcpu->policy->cpus) { pjcpu = &per_cpu(cpuinfo, j); fvt = max(fvt, pjcpu->local_fvtime); if (pjcpu->target_freq > max_freq) { max_freq = pjcpu->target_freq; hvt = pjcpu->local_hvtime; } else if (pjcpu->target_freq == max_freq) { hvt = min(hvt, pjcpu->local_hvtime); } } for_each_cpu(j, pcpu->policy->cpus) { pjcpu = &per_cpu(cpuinfo, j); pjcpu->floor_validate_time = fvt; } if (max_freq != pcpu->policy->cur) { __cpufreq_driver_target(pcpu->policy, max_freq, CPUFREQ_RELATION_H); for_each_cpu(j, pcpu->policy->cpus) { pjcpu = &per_cpu(cpuinfo, j); pjcpu->hispeed_validate_time = hvt; } } trace_cpufreq_interactive_setspeed(cpu, pcpu->target_freq, pcpu->policy->cur); up_read(&pcpu->enable_sem); } } return 0; } static int load_change_callback(struct notifier_block *nb, unsigned long val, void *data) { unsigned long cpu = (unsigned long) data; struct cpufreq_interactive_cpuinfo *pcpu = &per_cpu(cpuinfo, cpu); struct cpufreq_interactive_tunables *tunables; if (speedchange_task == current) return 0; if (pcpu->reject_notification) return 0; if (!down_read_trylock(&pcpu->enable_sem)) return 0; if (!pcpu->governor_enabled) { up_read(&pcpu->enable_sem); return 0; } tunables = pcpu->policy->governor_data; if (!tunables->use_sched_load || !tunables->use_migration_notif) { up_read(&pcpu->enable_sem); return 0; } trace_cpufreq_interactive_load_change(cpu); del_timer(&pcpu->cpu_timer); del_timer(&pcpu->cpu_slack_timer); cpufreq_interactive_timer(cpu); up_read(&pcpu->enable_sem); return 0; } static struct notifier_block load_notifier_block = { .notifier_call = load_change_callback, }; static int cpufreq_interactive_notifier( struct notifier_block *nb, unsigned long val, void *data) { struct cpufreq_freqs *freq = data; struct cpufreq_interactive_cpuinfo *pcpu; int cpu; unsigned long flags; if (val == CPUFREQ_PRECHANGE) { pcpu = &per_cpu(cpuinfo, freq->cpu); if (!down_read_trylock(&pcpu->enable_sem)) return 0; if (!pcpu->governor_enabled) { up_read(&pcpu->enable_sem); return 0; } for_each_cpu(cpu, pcpu->policy->cpus) { struct cpufreq_interactive_cpuinfo *pjcpu = &per_cpu(cpuinfo, cpu); if (cpu != freq->cpu) { if (!down_read_trylock(&pjcpu->enable_sem)) continue; if (!pjcpu->governor_enabled) { up_read(&pjcpu->enable_sem); continue; } } spin_lock_irqsave(&pjcpu->load_lock, flags); update_load(cpu); spin_unlock_irqrestore(&pjcpu->load_lock, flags); if (cpu != freq->cpu) up_read(&pjcpu->enable_sem); } up_read(&pcpu->enable_sem); } return 0; } static struct notifier_block cpufreq_notifier_block = { .notifier_call = cpufreq_interactive_notifier, }; static unsigned int *get_tokenized_data(const char *buf, int *num_tokens) { const char *cp; int i; int ntokens = 1; unsigned int *tokenized_data; int err = -EINVAL; cp = buf; while ((cp = strpbrk(cp + 1, " :"))) ntokens++; if (!(ntokens & 0x1)) goto err; tokenized_data = kmalloc(ntokens * sizeof(unsigned int), GFP_KERNEL); if (!tokenized_data) { err = -ENOMEM; goto err; } cp = buf; i = 0; while (i < ntokens) { if (sscanf(cp, "%u", &tokenized_data[i++]) != 1) goto err_kfree; cp = strpbrk(cp, " :"); if (!cp) break; cp++; } if (i != ntokens) goto err_kfree; *num_tokens = ntokens; return tokenized_data; err_kfree: kfree(tokenized_data); err: return ERR_PTR(err); } static ssize_t show_target_loads( struct cpufreq_interactive_tunables *tunables, char *buf) { int i; ssize_t ret = 0; unsigned long flags; spin_lock_irqsave(&tunables->target_loads_lock, flags); for (i = 0; i < tunables->ntarget_loads; i++) ret += sprintf(buf + ret, "%u%s", tunables->target_loads[i], i & 0x1 ? ":" : " "); sprintf(buf + ret - 1, "\n"); spin_unlock_irqrestore(&tunables->target_loads_lock, flags); return ret; } static ssize_t store_target_loads( struct cpufreq_interactive_tunables *tunables, const char *buf, size_t count) { int ntokens; unsigned int *new_target_loads = NULL; unsigned long flags; new_target_loads = get_tokenized_data(buf, &ntokens); if (IS_ERR(new_target_loads)) return PTR_RET(new_target_loads); spin_lock_irqsave(&tunables->target_loads_lock, flags); if (tunables->target_loads != default_target_loads) kfree(tunables->target_loads); tunables->target_loads = new_target_loads; tunables->ntarget_loads = ntokens; spin_unlock_irqrestore(&tunables->target_loads_lock, flags); return count; } static ssize_t show_above_hispeed_delay( struct cpufreq_interactive_tunables *tunables, char *buf) { int i; ssize_t ret = 0; unsigned long flags; spin_lock_irqsave(&tunables->above_hispeed_delay_lock, flags); for (i = 0; i < tunables->nabove_hispeed_delay; i++) ret += sprintf(buf + ret, "%u%s", tunables->above_hispeed_delay[i], i & 0x1 ? ":" : " "); sprintf(buf + ret - 1, "\n"); spin_unlock_irqrestore(&tunables->above_hispeed_delay_lock, flags); return ret; } static ssize_t store_above_hispeed_delay( struct cpufreq_interactive_tunables *tunables, const char *buf, size_t count) { int ntokens; unsigned int *new_above_hispeed_delay = NULL; unsigned long flags; new_above_hispeed_delay = get_tokenized_data(buf, &ntokens); if (IS_ERR(new_above_hispeed_delay)) return PTR_RET(new_above_hispeed_delay); spin_lock_irqsave(&tunables->above_hispeed_delay_lock, flags); if (tunables->above_hispeed_delay != default_above_hispeed_delay) kfree(tunables->above_hispeed_delay); tunables->above_hispeed_delay = new_above_hispeed_delay; tunables->nabove_hispeed_delay = ntokens; spin_unlock_irqrestore(&tunables->above_hispeed_delay_lock, flags); return count; } static ssize_t show_hispeed_freq(struct cpufreq_interactive_tunables *tunables, char *buf) { return sprintf(buf, "%u\n", tunables->hispeed_freq); } static ssize_t store_hispeed_freq(struct cpufreq_interactive_tunables *tunables, const char *buf, size_t count) { int ret; long unsigned int val; ret = strict_strtoul(buf, 0, &val); if (ret < 0) return ret; tunables->hispeed_freq = val; return count; } #define show_store_one(file_name) \ static ssize_t show_##file_name( \ struct cpufreq_interactive_tunables *tunables, char *buf) \ { \ return snprintf(buf, PAGE_SIZE, "%u\n", tunables->file_name); \ } \ static ssize_t store_##file_name( \ struct cpufreq_interactive_tunables *tunables, \ const char *buf, size_t count) \ { \ int ret; \ long unsigned int val; \ \ ret = kstrtoul(buf, 0, &val); \ if (ret < 0) \ return ret; \ tunables->file_name = val; \ return count; \ } show_store_one(max_freq_hysteresis); show_store_one(align_windows); static ssize_t show_go_hispeed_load(struct cpufreq_interactive_tunables *tunables, char *buf) { return sprintf(buf, "%lu\n", tunables->go_hispeed_load); } static ssize_t store_go_hispeed_load(struct cpufreq_interactive_tunables *tunables, const char *buf, size_t count) { int ret; unsigned long val; ret = strict_strtoul(buf, 0, &val); if (ret < 0) return ret; tunables->go_hispeed_load = val; return count; } static ssize_t show_min_sample_time(struct cpufreq_interactive_tunables *tunables, char *buf) { return sprintf(buf, "%lu\n", tunables->min_sample_time); } static ssize_t store_min_sample_time(struct cpufreq_interactive_tunables *tunables, const char *buf, size_t count) { int ret; unsigned long val; ret = strict_strtoul(buf, 0, &val); if (ret < 0) return ret; tunables->min_sample_time = val; return count; } static ssize_t show_timer_rate(struct cpufreq_interactive_tunables *tunables, char *buf) { return sprintf(buf, "%lu\n", tunables->timer_rate); } static ssize_t store_timer_rate(struct cpufreq_interactive_tunables *tunables, const char *buf, size_t count) { int ret; unsigned long val, val_round; struct cpufreq_interactive_tunables *t; int cpu; ret = strict_strtoul(buf, 0, &val); if (ret < 0) return ret; val_round = jiffies_to_usecs(usecs_to_jiffies(val)); if (val != val_round) pr_warn("timer_rate not aligned to jiffy. Rounded up to %lu\n", val_round); tunables->timer_rate = val_round; if (!tunables->use_sched_load) return count; for_each_possible_cpu(cpu) { t = per_cpu(cpuinfo, cpu).cached_tunables; if (t && t->use_sched_load) t->timer_rate = val_round; } set_window_helper(tunables); return count; } static ssize_t show_timer_slack(struct cpufreq_interactive_tunables *tunables, char *buf) { return sprintf(buf, "%d\n", tunables->timer_slack_val); } static ssize_t store_timer_slack(struct cpufreq_interactive_tunables *tunables, const char *buf, size_t count) { int ret; unsigned long val; ret = kstrtol(buf, 10, &val); if (ret < 0) return ret; tunables->timer_slack_val = val; return count; } static ssize_t show_boostpulse_duration(struct cpufreq_interactive_tunables *tunables, char *buf) { return sprintf(buf, "%d\n", tunables->boostpulse_duration_val); } static ssize_t store_boostpulse_duration(struct cpufreq_interactive_tunables *tunables, const char *buf, size_t count) { int ret; unsigned long val; ret = kstrtoul(buf, 0, &val); if (ret < 0) return ret; tunables->boostpulse_duration_val = val; return count; } static ssize_t show_io_is_busy(struct cpufreq_interactive_tunables *tunables, char *buf) { return sprintf(buf, "%u\n", tunables->io_is_busy); } static ssize_t store_io_is_busy(struct cpufreq_interactive_tunables *tunables, const char *buf, size_t count) { int ret; unsigned long val; struct cpufreq_interactive_tunables *t; int cpu; ret = kstrtoul(buf, 0, &val); if (ret < 0) return ret; tunables->io_is_busy = val; if (!tunables->use_sched_load) return count; for_each_possible_cpu(cpu) { t = per_cpu(cpuinfo, cpu).cached_tunables; if (t && t->use_sched_load) t->io_is_busy = val; } sched_set_io_is_busy(val); return count; } static int cpufreq_interactive_enable_sched_input( struct cpufreq_interactive_tunables *tunables) { int rc = 0, j; struct cpufreq_interactive_tunables *t; mutex_lock(&sched_lock); set_window_count++; if (set_window_count > 1) { for_each_possible_cpu(j) { t = per_cpu(cpuinfo, j).cached_tunables; if (t && t->use_sched_load) { tunables->timer_rate = t->timer_rate; tunables->io_is_busy = t->io_is_busy; break; } } } else { rc = set_window_helper(tunables); if (rc) { pr_err("%s: Failed to set sched window\n", __func__); set_window_count--; goto out; } sched_set_io_is_busy(tunables->io_is_busy); } if (!tunables->use_migration_notif) goto out; migration_register_count++; if (migration_register_count > 1) goto out; else atomic_notifier_chain_register(&load_alert_notifier_head, &load_notifier_block); out: mutex_unlock(&sched_lock); return rc; } static int cpufreq_interactive_disable_sched_input( struct cpufreq_interactive_tunables *tunables) { mutex_lock(&sched_lock); if (tunables->use_migration_notif) { migration_register_count--; if (migration_register_count < 1) atomic_notifier_chain_unregister( &load_alert_notifier_head, &load_notifier_block); } set_window_count--; mutex_unlock(&sched_lock); return 0; } static ssize_t show_use_sched_load( struct cpufreq_interactive_tunables *tunables, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", tunables->use_sched_load); } static ssize_t store_use_sched_load( struct cpufreq_interactive_tunables *tunables, const char *buf, size_t count) { int ret; unsigned long val; ret = kstrtoul(buf, 0, &val); if (ret < 0) return ret; if (tunables->use_sched_load == (bool) val) return count; tunables->use_sched_load = val; if (val) ret = cpufreq_interactive_enable_sched_input(tunables); else ret = cpufreq_interactive_disable_sched_input(tunables); if (ret) { tunables->use_sched_load = !val; return ret; } return count; } static ssize_t show_use_migration_notif( struct cpufreq_interactive_tunables *tunables, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", tunables->use_migration_notif); } static ssize_t store_use_migration_notif( struct cpufreq_interactive_tunables *tunables, const char *buf, size_t count) { int ret; unsigned long val; ret = kstrtoul(buf, 0, &val); if (ret < 0) return ret; if (tunables->use_migration_notif == (bool) val) return count; tunables->use_migration_notif = val; if (!tunables->use_sched_load) return count; mutex_lock(&sched_lock); if (val) { migration_register_count++; if (migration_register_count == 1) atomic_notifier_chain_register( &load_alert_notifier_head, &load_notifier_block); } else { migration_register_count--; if (!migration_register_count) atomic_notifier_chain_unregister( &load_alert_notifier_head, &load_notifier_block); } mutex_unlock(&sched_lock); return count; } /* * Create show/store routines * - sys: One governor instance for complete SYSTEM * - pol: One governor instance per struct cpufreq_policy */ #define show_gov_pol_sys(file_name) \ static ssize_t show_##file_name##_gov_sys \ (struct kobject *kobj, struct attribute *attr, char *buf) \ { \ return show_##file_name(common_tunables, buf); \ } \ \ static ssize_t show_##file_name##_gov_pol \ (struct cpufreq_policy *policy, char *buf) \ { \ return show_##file_name(policy->governor_data, buf); \ } #define store_gov_pol_sys(file_name) \ static ssize_t store_##file_name##_gov_sys \ (struct kobject *kobj, struct attribute *attr, const char *buf, \ size_t count) \ { \ return store_##file_name(common_tunables, buf, count); \ } \ \ static ssize_t store_##file_name##_gov_pol \ (struct cpufreq_policy *policy, const char *buf, size_t count) \ { \ return store_##file_name(policy->governor_data, buf, count); \ } #define show_store_gov_pol_sys(file_name) \ show_gov_pol_sys(file_name); \ store_gov_pol_sys(file_name) show_store_gov_pol_sys(target_loads); show_store_gov_pol_sys(above_hispeed_delay); show_store_gov_pol_sys(hispeed_freq); show_store_gov_pol_sys(go_hispeed_load); show_store_gov_pol_sys(min_sample_time); show_store_gov_pol_sys(timer_rate); show_store_gov_pol_sys(timer_slack); show_store_gov_pol_sys(boostpulse_duration); show_store_gov_pol_sys(io_is_busy); show_store_gov_pol_sys(use_sched_load); show_store_gov_pol_sys(use_migration_notif); show_store_gov_pol_sys(max_freq_hysteresis); show_store_gov_pol_sys(align_windows); #define gov_sys_attr_rw(_name) \ static struct global_attr _name##_gov_sys = \ __ATTR(_name, 0644, show_##_name##_gov_sys, store_##_name##_gov_sys) #define gov_pol_attr_rw(_name) \ static struct freq_attr _name##_gov_pol = \ __ATTR(_name, 0644, show_##_name##_gov_pol, store_##_name##_gov_pol) #define gov_sys_pol_attr_rw(_name) \ gov_sys_attr_rw(_name); \ gov_pol_attr_rw(_name) gov_sys_pol_attr_rw(target_loads); gov_sys_pol_attr_rw(above_hispeed_delay); gov_sys_pol_attr_rw(hispeed_freq); gov_sys_pol_attr_rw(go_hispeed_load); gov_sys_pol_attr_rw(min_sample_time); gov_sys_pol_attr_rw(timer_rate); gov_sys_pol_attr_rw(timer_slack); gov_sys_pol_attr_rw(boostpulse_duration); gov_sys_pol_attr_rw(io_is_busy); gov_sys_pol_attr_rw(use_sched_load); gov_sys_pol_attr_rw(use_migration_notif); gov_sys_pol_attr_rw(max_freq_hysteresis); gov_sys_pol_attr_rw(align_windows); /* One Governor instance for entire system */ static struct attribute *interactive_attributes_gov_sys[] = { &target_loads_gov_sys.attr, &above_hispeed_delay_gov_sys.attr, &hispeed_freq_gov_sys.attr, &go_hispeed_load_gov_sys.attr, &min_sample_time_gov_sys.attr, &timer_rate_gov_sys.attr, &timer_slack_gov_sys.attr, &boostpulse_duration_gov_sys.attr, &io_is_busy_gov_sys.attr, &use_sched_load_gov_sys.attr, &use_migration_notif_gov_sys.attr, &max_freq_hysteresis_gov_sys.attr, &align_windows_gov_sys.attr, NULL, }; static struct attribute_group interactive_attr_group_gov_sys = { .attrs = interactive_attributes_gov_sys, .name = "interactive", }; /* Per policy governor instance */ static struct attribute *interactive_attributes_gov_pol[] = { &target_loads_gov_pol.attr, &above_hispeed_delay_gov_pol.attr, &hispeed_freq_gov_pol.attr, &go_hispeed_load_gov_pol.attr, &min_sample_time_gov_pol.attr, &timer_rate_gov_pol.attr, &timer_slack_gov_pol.attr, &boostpulse_duration_gov_pol.attr, &io_is_busy_gov_pol.attr, &use_sched_load_gov_pol.attr, &use_migration_notif_gov_pol.attr, &max_freq_hysteresis_gov_pol.attr, &align_windows_gov_pol.attr, NULL, }; static struct attribute_group interactive_attr_group_gov_pol = { .attrs = interactive_attributes_gov_pol, .name = "interactive", }; static struct attribute_group *get_sysfs_attr(void) { if (have_governor_per_policy()) return &interactive_attr_group_gov_pol; else return &interactive_attr_group_gov_sys; } static int cpufreq_interactive_idle_notifier(struct notifier_block *nb, unsigned long val, void *data) { if (val == IDLE_END) cpufreq_interactive_idle_end(); return 0; } static struct notifier_block cpufreq_interactive_idle_nb = { .notifier_call = cpufreq_interactive_idle_notifier, }; static void save_tunables(struct cpufreq_policy *policy, struct cpufreq_interactive_tunables *tunables) { int cpu; struct cpufreq_interactive_cpuinfo *pcpu; if (have_governor_per_policy()) cpu = cpumask_first(policy->related_cpus); else cpu = 0; pcpu = &per_cpu(cpuinfo, cpu); WARN_ON(pcpu->cached_tunables && pcpu->cached_tunables != tunables); pcpu->cached_tunables = tunables; } static struct cpufreq_interactive_tunables *alloc_tunable( struct cpufreq_policy *policy) { struct cpufreq_interactive_tunables *tunables; tunables = kzalloc(sizeof(*tunables), GFP_KERNEL); if (!tunables) { pr_err("%s: POLICY_INIT: kzalloc failed\n", __func__); return ERR_PTR(-ENOMEM); } tunables->above_hispeed_delay = default_above_hispeed_delay; tunables->nabove_hispeed_delay = ARRAY_SIZE(default_above_hispeed_delay); tunables->go_hispeed_load = DEFAULT_GO_HISPEED_LOAD; tunables->target_loads = default_target_loads; tunables->ntarget_loads = ARRAY_SIZE(default_target_loads); tunables->min_sample_time = DEFAULT_MIN_SAMPLE_TIME; tunables->timer_rate = DEFAULT_TIMER_RATE; tunables->boostpulse_duration_val = DEFAULT_MIN_SAMPLE_TIME; tunables->timer_slack_val = DEFAULT_TIMER_SLACK; spin_lock_init(&tunables->target_loads_lock); spin_lock_init(&tunables->above_hispeed_delay_lock); save_tunables(policy, tunables); return tunables; } static struct cpufreq_interactive_tunables *restore_tunables( struct cpufreq_policy *policy) { int cpu; if (have_governor_per_policy()) cpu = cpumask_first(policy->related_cpus); else cpu = 0; return per_cpu(cpuinfo, cpu).cached_tunables; } static int cpufreq_governor_interactive(struct cpufreq_policy *policy, unsigned int event) { int rc; unsigned int j; struct cpufreq_interactive_cpuinfo *pcpu; struct cpufreq_frequency_table *freq_table; struct cpufreq_interactive_tunables *tunables; unsigned long flags; int first_cpu; if (have_governor_per_policy()) tunables = policy->governor_data; else tunables = common_tunables; BUG_ON(!tunables && (event != CPUFREQ_GOV_POLICY_INIT)); switch (event) { case CPUFREQ_GOV_POLICY_INIT: if (have_governor_per_policy()) { WARN_ON(tunables); } else if (tunables) { tunables->usage_count++; policy->governor_data = tunables; return 0; } first_cpu = cpumask_first(policy->related_cpus); for_each_cpu(j, policy->related_cpus) per_cpu(cpuinfo, j).first_cpu = first_cpu; tunables = restore_tunables(policy); if (!tunables) { tunables = alloc_tunable(policy); if (IS_ERR(tunables)) return PTR_ERR(tunables); } tunables->usage_count = 1; policy->governor_data = tunables; if (!have_governor_per_policy()) { WARN_ON(cpufreq_get_global_kobject()); common_tunables = tunables; } rc = sysfs_create_group(get_governor_parent_kobj(policy), get_sysfs_attr()); if (rc) { kfree(tunables); policy->governor_data = NULL; if (!have_governor_per_policy()) { common_tunables = NULL; cpufreq_put_global_kobject(); } return rc; } if (!policy->governor->initialized) { idle_notifier_register(&cpufreq_interactive_idle_nb); cpufreq_register_notifier(&cpufreq_notifier_block, CPUFREQ_TRANSITION_NOTIFIER); } if (tunables->use_sched_load) cpufreq_interactive_enable_sched_input(tunables); break; case CPUFREQ_GOV_POLICY_EXIT: if (!--tunables->usage_count) { if (policy->governor->initialized == 1) { cpufreq_unregister_notifier(&cpufreq_notifier_block, CPUFREQ_TRANSITION_NOTIFIER); idle_notifier_unregister(&cpufreq_interactive_idle_nb); } sysfs_remove_group(get_governor_parent_kobj(policy), get_sysfs_attr()); if (!have_governor_per_policy()) cpufreq_put_global_kobject(); common_tunables = NULL; } policy->governor_data = NULL; if (tunables->use_sched_load) cpufreq_interactive_disable_sched_input(tunables); break; case CPUFREQ_GOV_START: mutex_lock(&gov_lock); freq_table = cpufreq_frequency_get_table(policy->cpu); if (!tunables->hispeed_freq) tunables->hispeed_freq = policy->max; for_each_cpu(j, policy->cpus) { pcpu = &per_cpu(cpuinfo, j); pcpu->policy = policy; pcpu->target_freq = policy->cur; pcpu->freq_table = freq_table; pcpu->floor_freq = pcpu->target_freq; pcpu->floor_validate_time = ktime_to_us(ktime_get()); pcpu->local_fvtime = pcpu->floor_validate_time; pcpu->hispeed_validate_time = pcpu->floor_validate_time; pcpu->local_hvtime = pcpu->floor_validate_time; pcpu->max_freq = policy->max; pcpu->min_freq = policy->min; pcpu->reject_notification = true; down_write(&pcpu->enable_sem); del_timer_sync(&pcpu->cpu_timer); del_timer_sync(&pcpu->cpu_slack_timer); pcpu->last_evaluated_jiffy = get_jiffies_64(); cpufreq_interactive_timer_start(tunables, j); pcpu->governor_enabled = 1; up_write(&pcpu->enable_sem); pcpu->reject_notification = false; } mutex_unlock(&gov_lock); break; case CPUFREQ_GOV_STOP: mutex_lock(&gov_lock); for_each_cpu(j, policy->cpus) { pcpu = &per_cpu(cpuinfo, j); pcpu->reject_notification = true; down_write(&pcpu->enable_sem); pcpu->governor_enabled = 0; pcpu->target_freq = 0; del_timer_sync(&pcpu->cpu_timer); del_timer_sync(&pcpu->cpu_slack_timer); up_write(&pcpu->enable_sem); pcpu->reject_notification = false; } mutex_unlock(&gov_lock); break; case CPUFREQ_GOV_LIMITS: __cpufreq_driver_target(policy, policy->cur, CPUFREQ_RELATION_L); for_each_cpu(j, policy->cpus) { pcpu = &per_cpu(cpuinfo, j); down_read(&pcpu->enable_sem); if (pcpu->governor_enabled == 0) { up_read(&pcpu->enable_sem); continue; } spin_lock_irqsave(&pcpu->target_freq_lock, flags); if (policy->max < pcpu->target_freq) pcpu->target_freq = policy->max; else if (policy->min > pcpu->target_freq) pcpu->target_freq = policy->min; spin_unlock_irqrestore(&pcpu->target_freq_lock, flags); if (policy->min < pcpu->min_freq) cpufreq_interactive_timer_resched(j, true); pcpu->min_freq = policy->min; up_read(&pcpu->enable_sem); /* Reschedule timer only if policy->max is raised. * Delete the timers, else the timer callback may * return without re-arm the timer when failed * acquire the semaphore. This race may cause timer * stopped unexpectedly. */ if (policy->max > pcpu->max_freq) { pcpu->reject_notification = true; down_write(&pcpu->enable_sem); del_timer_sync(&pcpu->cpu_timer); del_timer_sync(&pcpu->cpu_slack_timer); cpufreq_interactive_timer_resched(j, false); up_write(&pcpu->enable_sem); pcpu->reject_notification = false; } pcpu->max_freq = policy->max; } break; } return 0; } #ifndef CONFIG_CPU_FREQ_DEFAULT_GOV_INTERACTIVE static #endif struct cpufreq_governor cpufreq_gov_interactive = { .name = "interactive", .governor = cpufreq_governor_interactive, .max_transition_latency = 10000000, .owner = THIS_MODULE, }; static void cpufreq_interactive_nop_timer(unsigned long data) { } static int __init cpufreq_interactive_init(void) { unsigned int i; struct cpufreq_interactive_cpuinfo *pcpu; struct sched_param param = { .sched_priority = MAX_RT_PRIO-1 }; /* Initalize per-cpu timers */ for_each_possible_cpu(i) { pcpu = &per_cpu(cpuinfo, i); init_timer_deferrable(&pcpu->cpu_timer); pcpu->cpu_timer.function = cpufreq_interactive_timer; pcpu->cpu_timer.data = i; init_timer(&pcpu->cpu_slack_timer); pcpu->cpu_slack_timer.function = cpufreq_interactive_nop_timer; spin_lock_init(&pcpu->load_lock); spin_lock_init(&pcpu->target_freq_lock); init_rwsem(&pcpu->enable_sem); } spin_lock_init(&speedchange_cpumask_lock); mutex_init(&gov_lock); mutex_init(&sched_lock); speedchange_task = kthread_create(cpufreq_interactive_speedchange_task, NULL, "cfinteractive"); if (IS_ERR(speedchange_task)) return PTR_ERR(speedchange_task); sched_setscheduler_nocheck(speedchange_task, SCHED_FIFO, &param); get_task_struct(speedchange_task); /* NB: wake up so the thread does not look hung to the freezer */ wake_up_process(speedchange_task); return cpufreq_register_governor(&cpufreq_gov_interactive); } #ifdef CONFIG_CPU_FREQ_DEFAULT_GOV_INTERACTIVE fs_initcall(cpufreq_interactive_init); #else module_init(cpufreq_interactive_init); #endif static void __exit cpufreq_interactive_exit(void) { int cpu; struct cpufreq_interactive_cpuinfo *pcpu; cpufreq_unregister_governor(&cpufreq_gov_interactive); kthread_stop(speedchange_task); put_task_struct(speedchange_task); for_each_possible_cpu(cpu) { pcpu = &per_cpu(cpuinfo, cpu); kfree(pcpu->cached_tunables); pcpu->cached_tunables = NULL; } } module_exit(cpufreq_interactive_exit); MODULE_AUTHOR("Mike Chan <mike@android.com>"); MODULE_DESCRIPTION("'cpufreq_interactive' - A cpufreq governor for " "Latency sensitive workloads"); MODULE_LICENSE("GPL");
auras76/aur-kernel-XZxx
drivers/cpufreq/cpufreq_interactive.c
C
gpl-2.0
45,081
#!/usr/bin/env python from __future__ import print_function import argparse import os import sys def main(): args = parseArgs(sys.argv) # get analogy files in the analogy directory # http://stackoverflow.com/questions/3207219/how-to-list-all-files-of-a-directory-in-python resultFns = [os.path.join(args.results, fn) for fn in next(os.walk(args.results))[2]] glbCorrCnt = 0 glbLineCnt = 0 semCorrCnt = 0 semLineCnt = 0 synCorrCnt = 0 synLineCnt = 0 for resultFn in resultFns: lineCnt = 0 corrCnt = 0 ansInQuCnt = 0 with open(resultFn, 'rb') as resultF: # print(resultFn) for result in resultF: words = result.split() # print(words) if words[4] == '**NO_EMBEDDING_FOR_A_WORD**': continue if len(words) < 5: break if words[3] == words[4]: corrCnt += 1 if words[4] in words[:3]: ansInQuCnt += 1 lineCnt += 1 if lineCnt < 1: continue acc = float(corrCnt) / lineCnt ansInQu = float(ansInQuCnt) / lineCnt print('{:s} {:0.3f} {:0.3f}'.format( os.path.basename(resultFn), acc, ansInQu)) glbLineCnt += lineCnt glbCorrCnt += corrCnt if os.path.basename(resultFn).startswith('gram'): synCorrCnt += corrCnt synLineCnt += lineCnt else: semCorrCnt += corrCnt semLineCnt += lineCnt if semLineCnt > 0: print('Sem Av {:0.3f}'.format(float(semCorrCnt) / semLineCnt)) if synLineCnt > 0: print('Syn Av {:0.3f}'.format(float(synCorrCnt) / synLineCnt)) print('Average {:0.3f}'.format(float(glbCorrCnt) / glbLineCnt)) def parseArgs(args): parser = argparse.ArgumentParser( description='Evaluate analogy results. Written in Python 2.7.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('results', type=validDirectory, help='The directory containing result files.') return parser.parse_args() def validDirectory(dirName): if os.path.isdir(dirName): return dirName msg = 'Directory "{:s}" does not exist.'.format(dirName) raise argparse.ArgumentTypeError(msg) if __name__ == '__main__': main()
ppegusii/cs689-mini1
src/evaluate.py
Python
gpl-2.0
2,517
<?php /** * WURFL API * * LICENSE * * This file is released under the GNU General Public License. Refer to the * COPYING file distributed with this package. * * Copyright (c) 2008-2009, WURFL-Pro S.r.l., Rome, Italy * * * * @category WURFL * @package WURFL_Handlers * @copyright WURFL-PRO SRL, Rome, Italy * @license * @version $id$ */ /** * KDDIUserAgentHandler * * * @category WURFL * @package WURFL_Handlers * @copyright WURFL-PRO SRL, Rome, Italy * @license * @version $id$ */ class WURFL_Handlers_KDDIHandler extends WURFL_Handlers_Handler { protected $prefix = "KDDI"; function __construct($wurflContext, $userAgentNormalizer = null) { parent::__construct ( $wurflContext, $userAgentNormalizer ); } /** * Intercept all UAs containing "KDDI" * * @param string $userAgent * @return boolean */ public function canHandle($userAgent) { return WURFL_Handlers_Utils::checkIfContains ( $userAgent, "KDDI" ); } /** */ function lookForMatchingUserAgent($userAgent) { $tolerance = $this->tolerance ( $userAgent ); return WURFL_Handlers_Utils::risMatch ( array_keys ( $this->userAgentsWithDeviceID ), $userAgent, $tolerance ); } /** * * @param string $userAgent * @return string */ function applyRecoveryMatch($userAgent) { if (WURFL_Handlers_Utils::checkIfContains ( $userAgent, "Opera" )) { return "opera"; } return "opwv_v62_generic"; } private function tolerance($userAgent) { if (WURFL_Handlers_Utils::checkIfStartsWith ( $userAgent, "KDDI/" )) { return WURFL_Handlers_Utils::secondSlash ( $userAgent ); } if (WURFL_Handlers_Utils::checkIfStartsWith ( $userAgent, "KDDI" )) { return WURFL_Handlers_Utils::firstSlash ( $userAgent ); } return WURFL_Handlers_Utils::indexOfOrLength ( $userAgent, ")" ); } } ?>
chisimba/modules
wurfl/resources/WURFL/Handlers/KDDIHandler.php
PHP
gpl-2.0
1,840
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <HTML> <HEAD> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <META name="GENERATOR" content="hevea 1.10"> <LINK rel="stylesheet" type="text/css" href="cascmd_fr.css"> <TITLE>Remarques générales sur l’affichage des mesures</TITLE> </HEAD> <BODY > <A HREF="cascmd_fr938.html"><IMG SRC="previous_motif.gif" ALT="Previous"></A> <A HREF="index.html"><IMG SRC="contents_motif.gif" ALT="Up"></A> <A HREF="cascmd_fr940.html"><IMG SRC="next_motif.gif" ALT="Next"></A> <HR> <H3 CLASS="subsection"><A NAME="htoc1104">10.16.1</A>  Remarques générales sur l’affichage des mesures</H3><P><A NAME="@default1811"></A><A NAME="@default1812"></A><A NAME="@default1813"></A><A NAME="@default1814"></A><A NAME="@default1815"></A><A NAME="@default1816"></A> Les commandes concernant les mesures et se terminant pas <TT>en</TT> ou <TT>at</TT> (resp <TT>enbrut</TT> ou <TT>atraw</TT>) gérent l’affichage de ces mesures en un point (qui est le dernier argument de ces commandes) avec une légende succinte (resp sans légende). Si on préfère une légende plus sophistiquée il faut utiliser la commande <TT>legende</TT> ou <TT>affichage</TT> avec <TT>legende</TT> comme argument. On tape par exemple : </P><DIV CLASS="center"><TT>C:=carre(0,1);a:=aire(C);p:=perimetre(C)</TT></DIV><DIV CLASS="center"><TT>legend(1+i,"aire(C)="+string(a))</TT></DIV><P> On obtient : </P><DIV CLASS="center"><TT>aire(C)=1 s’écrit au d’affixe 1+i</TT></DIV><P> puis, on tape : </P><DIV CLASS="center"><TT>affichage(legend(1,"perimetre(C)="+string(p)),vert)</TT></DIV><P>On obtient : </P><DIV CLASS="center"><TT>perimetre(C)=4 s’écrit en vert au point 1</TT></DIV><P> alors que si on tape : </P><DIV CLASS="center"><TT>aireen(C,1+i)</TT></DIV><P> On obtient : </P><DIV CLASS="center"><TT>aC=1 s’écrit au d’affixe 1+i</TT></DIV><P> puis, si on tape : </P><DIV CLASS="center"><TT>perimetreen(C,1)</TT></DIV><P> On obtient : </P><DIV CLASS="center"><TT>pC=4 s’écrit au d’affixe 1</TT></DIV><P> ou bien si on tape : </P><DIV CLASS="center"><TT>aireenbrut(C,1+i)</TT></DIV><P> On obtient : </P><DIV CLASS="center"><TT>1 s’écrit au d’affixe 1+i</TT></DIV><P> puis, si on tape : </P><DIV CLASS="center"><TT>perimetreenbrut(C,1)</TT></DIV><P> On obtient : </P><DIV CLASS="center"><TT>4 s’écrit au d’affixe 1</TT></DIV><HR> <A HREF="cascmd_fr938.html"><IMG SRC="previous_motif.gif" ALT="Previous"></A> <A HREF="index.html"><IMG SRC="contents_motif.gif" ALT="Up"></A> <A HREF="cascmd_fr940.html"><IMG SRC="next_motif.gif" ALT="Next"></A> </BODY> </HTML>
hiplayer/giac
giac/giac-1.2.2/doc/fr/cascmd_fr/cascmd_fr939.html
HTML
gpl-2.0
2,687
<!DOCTYPE html> <html > <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <meta name="generator" content="hevea 2.29+5 of 2017-05-18"> <link rel="stylesheet" type="text/css" href="cascmd_en.css"> <title>Determinant of a matrix with coefficients in &#X2124;/p&#X2124; : Det</title> </head> <body > <a href="cascmd_en273.html"><img src="previous_motif.gif" alt="Previous"></a> <a href="index.html"><img src="contents_motif.gif" alt="Up"></a> <a href="cascmd_en275.html"><img src="next_motif.gif" alt="Next"></a> <hr> <h3 id="sec329" class="subsection">2.32.5  Determinant of a matrix with coefficients in &#X2124;/<span style="font-style:italic">p</span>&#X2124; : <span style="font-family:monospace">Det</span></h3> <p><a id="hevea_default473"></a> <span style="font-family:monospace">Det</span> is the inert form of <span style="font-family:monospace">det</span>.<br> <span style="font-family:monospace">Det</span> takes as argument a matrix with coefficients in &#X2124;/<span style="font-style:italic">p</span>&#X2124;.<br> <span style="font-family:monospace">Det</span> returns <span style="font-family:monospace">det</span> without evaluation. It is used in conjunction with <span style="font-family:monospace">mod</span> in Maple syntax mode to find the determinant of a matrix with coefficients in &#X2124;/<span style="font-style:italic">p</span>&#X2124;.<br> Input in <span style="font-family:monospace">Xcas</span> mode : </p><div class="center"><span style="font-family:monospace">Det([[1,2,9] mod 13,[3,10,0] mod 13,[3,11,1] mod 13])</span></div><p> Output : </p><div class="center"><span style="font-family:monospace">det([[1%13,2%13,-4%13],[3%13,-3%13,0%13], [3%13,-2%13,1%13]])</span></div><p> you need to <span style="font-family:monospace">eval(ans())</span> to get : </p><div class="center"><span style="font-family:monospace">5%13</span></div><p> hence, in &#X2124;/13&#X2124;, the determinant of <span style="font-style:italic">A</span>=[[1, 2, 9],[3,10,0],[3,11,1]] is <span style="font-family:monospace">5%13</span> (in &#X2124;, <span style="font-family:monospace">det(A)=31</span>).<br> Input in <span style="font-family:monospace">Maple</span> mode : </p><div class="center"><span style="font-family:monospace">Det([[1,2,9],[3,10,0],[3,11,1]]) mod 13</span></div><p> Output : </p><div class="center"><span style="font-family:monospace">5</span></div> <hr> <a href="cascmd_en273.html"><img src="previous_motif.gif" alt="Previous"></a> <a href="index.html"><img src="contents_motif.gif" alt="Up"></a> <a href="cascmd_en275.html"><img src="next_motif.gif" alt="Next"></a> </body> </html>
hiplayer/giac
giac/giac-1.2.3/doc/en/cascmd_en/cascmd_en274.html
HTML
gpl-2.0
2,643
package Servlets; import org.json.JSONException; import org.json.JSONObject; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; /** * Created by matan on 01/10/15. */ @WebServlet(name = "login") public class Logout extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); session.invalidate(); JSONObject result = new JSONObject(); try { result.put("success", 0); } catch (JSONException e) { e.printStackTrace(); } response.getWriter().print(result.toString()); } }
matanso/OASSIS
src/main/java/Servlets/Logout.java
Java
gpl-2.0
1,072
/* * Copyright (c) 1998-2010 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Emil Ong */ package com.caucho.jaxb.property; import javax.xml.bind.DatatypeConverter; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import java.io.IOException; import java.lang.reflect.Array; import java.util.Collection; public class XmlListBooleanArrayProperty extends XmlListArrayProperty { public XmlListBooleanArrayProperty() { super(BooleanProperty.PRIMITIVE_PROPERTY); } protected Object read(String in) throws IOException, JAXBException { String[] tokens = in.split("\\s+"); boolean[] array = new boolean[tokens.length]; for (int i = 0; i < tokens.length; i++) array[i] = DatatypeConverter.parseBoolean(tokens[i]); return array; } }
christianchristensen/resin
modules/extra/src/com/caucho/jaxb/property/XmlListBooleanArrayProperty.java
Java
gpl-2.0
1,852
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.similarities.AfterEffectL; import org.apache.lucene.search.similarities.BM25Similarity; import org.apache.lucene.search.similarities.BasicModelP; import org.apache.lucene.search.similarities.DFRSimilarity; import org.apache.lucene.search.similarities.LMDirichletSimilarity; import org.apache.lucene.search.similarities.NormalizationH2; import org.apache.lucene.search.similarities.Similarity; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; public class SearchOhsumedFiles { public static class SearchResult { public String queryId; public String results[]; public double scores[]; } private SearchOhsumedFiles() { } public static void main(String[] args) throws Exception { String index = null; String queries = null; String runId = null; float threshold = 0.0f; for (int i = 0; i < args.length; i++) { if ("-index".equals(args[i])) { index = args[i + 1]; i++; } else if ("-queries".equals(args[i])) { queries = args[i + 1]; i++; } else if ("-runid".equals(args[i])) { runId = args[i + 1]; i++; } else if ("-threshold".equals(args[i])) { threshold = Float.parseFloat(args[i + 1]); i++; } } Similarity simfn = null; if ("bm25".equals(runId)) { simfn = new BM25Similarity(); } else if ("dfr".equals(runId)) { simfn = new DFRSimilarity(new BasicModelP(), new AfterEffectL(), new NormalizationH2()); } else if ("lm".equals(runId)) { simfn = new LMDirichletSimilarity(); } else { throw new IllegalArgumentException("No such similarity model: " + runId); } runSearch(index, queries, runId, threshold, simfn); } public static Map<String, String[]> runSearch(String index, String queries, String runId, float threshold, Similarity simfn) throws IOException, ParseException { HashMap<String, String[]> results = new HashMap<String, String[]>(); IndexReader reader = DirectoryReader.open(FSDirectory.open(new File( index))); IndexSearcher searcher = new IndexSearcher(reader); searcher.setSimilarity(simfn); Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_41); BufferedReader in = null; if (queries != null) { in = new BufferedReader(new InputStreamReader(new FileInputStream( queries), "UTF-8")); } else { in = new BufferedReader(new InputStreamReader(System.in, "UTF-8")); } MultiFieldQueryParser queryParser = new MultiFieldQueryParser( Version.LUCENE_41, new String[] { "contents", "title" }, analyzer); String titleQ = null, contentQ = null; SearchResult searchResult = null; List<SearchResult> resultsList = new ArrayList<SearchResult>(); while (true) { assert (queries != null); String line = in.readLine(); if (line == null || line.length() == -1) { break; } if (line.contains("<top>")) { searchResult = new SearchResult(); resultsList.add(searchResult); continue; } else if (line.startsWith("<num>")) { assert (searchResult != null); searchResult.queryId = line.split(":")[1].trim(); } else if (line.startsWith("<title>")) { titleQ = line.split(">")[1].trim(); } else if (line.startsWith("<desc>")) { line = in.readLine(); contentQ = line; } else if (line.startsWith("</top>")) { // Query query = queryParser.parse(QueryParser.escape(titleQ) + // " " + // QueryParser.escape(contentQ)); BooleanQuery query = new BooleanQuery(); query.add(queryParser.parse(QueryParser.escape(titleQ)), BooleanClause.Occur.SHOULD); query.add(queryParser.parse(QueryParser.escape(contentQ)), BooleanClause.Occur.SHOULD); /* * Query query = queryParser.parse(Version.LUCENE_41, new * String[] { QueryParser.escape(contentQ), * QueryParser.escape(titleQ) }, new String[] { "contents", * "title" }, analyzer); */ // System.out.println("Searching for: " + // query.toString(field)); results.put( searchResult.queryId, performSearch(in, searcher, query, searchResult.queryId, runId == null ? "null" : runId, threshold)); } else { continue; } } reader.close(); return results; } public static String[] performSearch(BufferedReader in, IndexSearcher searcher, Query query, String queryId, String runId, float threshold) throws IOException { ArrayList<String> resultsList = new ArrayList<String>(); TopDocs results = searcher.search(query, 100); ScoreDoc[] hits = results.scoreDocs; // not sure if dataset may have duplicates HashSet<String> docSet = new HashSet<String>(); int start = 0; int end = 100; for (int i = start; i < end; i++) { Document doc = searcher.doc(hits[i].doc); String docno = doc.get("docno"); assert (docno != null); if (docSet.contains(docno)) continue; docSet.add(docno); if (isRelevant(threshold, hits[i].score / results.getMaxScore())) { String result = queryId + " Q0 " + docno + " " + i + " " + hits[i].score + " " + runId; resultsList.add(result); System.out.println(result); } else break; } return (String[]) resultsList.toArray(new String[resultsList.size()]); } private static boolean isRelevant(float threshold, float normalizedScore) { if ((normalizedScore - threshold) > 0.0000001) return true; return false; } }
darthcodus/Lucene-TREC-OHSUMED
src/SearchOhsumedFiles.java
Java
gpl-2.0
6,310
<?php class Xlib_XListaDados_FieldFilter_CPF extends Xlib_XListaDados_FieldFilterAbstract { private $punct = true; public function getInstance ( $field , $label = "" , $punct = false ) { return new Xlib_XListaDados_FieldFilter_CPF ( $field , $label , $punct ); } public function formatQueryFilter ( ) { $value = Request::get($this->filterContainer."[".$this->field."]"); if ( $value === "" ) return null ; if ( !$this->punct ) $value = preg_replace ( '/[^\d]+/' , '' , $value ); return eval ( "return \"" . $this->template . "\" ;") ; } public function getPunct ( ) { return $this->punct; } /** * Remove a pontuação para buscar no banco * @param [type] $punct [description] */ public function setPunct ( $punct ) { $this->punct = (bool) $punct ; return $this; } /** * * @param [type] $field [description] * @param string $label [description] * @param boolean $punct false se o CPF é salvo no banco sem pontuação. true se é salvo com pontuação */ public function __construct ( $field , $label = "" , $punct = false ) { $this->setField ( $field ); $this->setLabel ( $label ); $this->setPunct ( $punct ); } public function getFieldFormatter ( ) { $script = 'var tmp=this.value.replace(/[^\d]+/g,\'\');console.log(tmp);switch(tmp.length){case 0:case 1:case 2:case 3:return;case 4:case 5:case 6:this.value=tmp.replace(/^(\d{3})(\d+)/,\'$1.$2\');return;case 7:case 8:case 9:this.value=tmp.replace(/^(\d{3})(\d{3})(\d+)/,\'$1.$2.$3\');return;default:this.value=tmp.replace(/^(\d{3})(\d{3})(\d{3})(\d{1,2})(.*)/,\'$1.$2.$3-$4\')}' ; return $script ; } /** * Muitas vezes você vai querer sobrescrever este método * @return type */ public function __toString ( ) { $output = $this->getSufix() ; $attributeSet = $this->getAttributeSet ( ); $attributeSet['style'] = empty ( $attributeSet['style'] ) ? "width:125px" : $attributeSet['style'] . ";width:125px" ; $attributeSet['placeholder'] = "___.___.___-__"; $attributeSet['onKeyPress'] = $this->getFieldFormatter(); $attributeSet['onKeyUp'] = $this->getFieldFormatter(); $attributeSet['onKeyDown'] = $this->getFieldFormatter(); $attributeSet['maxlength'] = '14'; $labelAttributeSet = array ( 'for' => $attributeSet['id'] , "class" => "control-label" ); if ( empty ( $this->label ) ) $labelAttributeSet['class'] = 'sr-only'; $output .= "<div class=\"form-group\">"; $output .= "<label " . $this->getAttributeSetAsString ( $labelAttributeSet ) . " >" . $this->label . "</label><br/>" ; $output .= "<input " . $this->getAttributeSetAsString ( $attributeSet ) . " >"; $output .= "</div>"; // $output .= " // <script> // $(function(){ // $(\"#".$attributeSet['id']."\").datepicker(); // }); // </script> // " ; $output .= $this->getPrefix (); return $output; } }
hugoofab/XLibrary
XListaDados/FieldFilter/CPF.php
PHP
gpl-2.0
3,135
package FSMBuilder.FSMmodel; import FSMBuilder.FSMfunctions.constants.Ifile; import FSMBuilder.FSMfunctions.constants.Imisc; import java.awt.geom.Line2D; /** * Base class for all types of transitions * @author Logan Fine */ public abstract class Ctrans extends CbasicFSMObject { protected final Cnode m_from; protected final Cnode m_to; /** * Default constructor * @param from source node * @param to finish node */ public Ctrans(Cnode from, Cnode to) { super(); if (from != null && to != null) { m_from = from; m_to = to; } else throw new RuntimeException("Ctransition creation on null nodes"); } /** * from-node getter * @return Cnode */ public Cnode getFrom() { return m_from; } /** * to-node getter * @return Cnode */ public Cnode getTo() { return m_to; } @Override public boolean setLabel(Clabel l) { if (l != null) { m_label = l; m_label.parse_transition(); } return l != null; } @Override public boolean hasCoords(Integer x, Integer y) { if (x != null && y != null) { Line2D l = new Line2D.Double(m_from.m_center.m_x, m_from.m_center.m_y, m_to.m_center.m_x, m_to.m_center.m_y); int toleration = 10; int width = 20; int height = 20; return l.intersects(x - toleration, y - toleration, width, height); } return false; } @Override public String toString() { return Ifile.TYPE_TRANS + Ifile.DELIMITER + m_from.m_center.toString() + m_to.m_center.toString() + super.toString(); } @Override public boolean equals(Object other) { if (other == null || ! this.getClass().equals(other.getClass())) return false; if (other == this) return true; Ctrans t = (Ctrans) other; return m_from.equals(t.m_from) && m_to.equals(t.m_to) && m_label.equals(t.m_label); } @Override public int hashCode() { return Imisc.TRANS_HASH; } }
nzt4567/fsa
src/main/java/FSMBuilder/FSMmodel/Ctrans.java
Java
gpl-2.0
2,291
/* * Copyright (C) 2012 The Android Open Source Project * Copyright (C) 2012 The CyanogenMod Project <http://www.cyanogenmod.org> * * 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. */ #ifndef _BDROID_BUILDCFG_H #define _BDROID_BUILDCFG_H #define BTM_DEF_LOCAL_NAME "Samsung Galaxy Star" #endif
batman38102/android_device_samsung_mint
bluetooth/bdroid_buildcfg.h
C
gpl-2.0
810
<?php namespace Drupal\facets\Plugin\facets\query_type; use Drupal\facets\QueryType\QueryTypePluginBase; use Drupal\facets\Result\Result; /** * Provides support for range facets within the Search API scope. * * This is the default implementation that works with all backends. * * @FacetsQueryType( * id = "search_api_range", * label = @Translation("Range"), * ) */ class SearchApiRange extends QueryTypePluginBase { /** * The backend's native query object. * * @var \Drupal\search_api\Query\QueryInterface */ protected $query; /** * {@inheritdoc} */ public function execute() { $query = $this->query; // Only alter the query when there's an actual query object to alter. if (!empty($query)) { $operator = $this->facet->getQueryOperator(); $field_identifier = $this->facet->getFieldIdentifier(); $exclude = $this->facet->getExclude(); // Set the options for the actual query. $options = &$query->getOptions(); $options['search_api_facets'][$field_identifier] = [ 'field' => $field_identifier, 'limit' => $this->facet->getHardLimit(), 'operator' => $this->facet->getQueryOperator(), 'min_count' => $this->facet->getMinCount(), 'missing' => FALSE, ]; // Add the filter to the query if there are active values. $active_items = $this->facet->getActiveItems(); if (count($active_items)) { $filter = $query->createConditionGroup($operator, ['facet:' . $field_identifier]); foreach ($active_items as $value) { $filter->addCondition($field_identifier, $value, $exclude ? 'NOT BETWEEN' : 'BETWEEN'); } $query->addConditionGroup($filter); } } } /** * {@inheritdoc} */ public function build() { $query_operator = $this->facet->getQueryOperator(); if (!empty($this->results)) { $facet_results = []; foreach ($this->results as $key => $result) { if ($result['count'] || $query_operator == 'or') { $count = $result['count']; $result_filter = trim($result['filter'], '"'); $result = new Result($result_filter, $result_filter, $count); $facet_results[] = $result; } } $this->facet->setResults($facet_results); } return $this->facet; } }
YashiMalhotra/drupalsolr
modules/contrib/facets/src/Plugin/facets/query_type/SearchApiRange.php
PHP
gpl-2.0
2,345
#ifndef CLIENT_H #define CLIENT_H #include <QDialog> #include <QAbstractSocket> class QTcpSocket; class QFile; namespace Ui { class Client; } class Client : public QDialog { Q_OBJECT public: explicit Client(QWidget *parent = 0); ~Client(); private: Ui::Client *ui; QTcpSocket *tcpClient; QFile *localFile; // Òª·¢Ë͵ÄÎļþ qint64 totalBytes; // ·¢ËÍÊý¾ÝµÄ×Ü´óС qint64 bytesWritten; // ÒѾ­·¢ËÍÊý¾Ý´óС qint64 bytesToWrite; // Ê£ÓàÊý¾Ý´óС qint64 payloadSize; // ÿ´Î·¢ËÍÊý¾ÝµÄ´óС QString fileName; // ±£´æÎļþ·¾¶ QByteArray outBlock; // Êý¾Ý»º³åÇø£¬¼´´æ·Åÿ´ÎÒª·¢Ë͵ÄÊý¾Ý¿é private slots: void openFile(); void send(); void startTransfer(); void updateClientProgress(qint64); void displayError(QAbstractSocket::SocketError); void on_openButton_clicked(); void on_sendButton_clicked(); }; #endif // CLIENT_H
weiqiangdragonite/MyQtProject
learning_code/getting_started_qt_creator/Qt Creator快速入门_代码/src/18/18-8/tcpClient/client.h
C
gpl-2.0
908
<!--footer start here--> <div class="footer"> <div class="container"> <div class="footer-main"> <div class="col-md-4 footer-grid wow bounceIn" data-wow-delay="0.4s"> <h3>NUESTRA FILOSOFÍA </h3> <P>Gestionar y posicionar, de manera creativa y auténtica, la imagen como empleador de una compañía como elemento de atracción, motivación y retención de actuales empleados y potenciales.</P> <h5>Contacto:<br> <a href="mailto:indentidadesrh@gmail.com">indentidadesrh@gmail.com</a></h5> <h6>(809)329-9393</h6> <h5>Siguenos en:</h5> <a href="http://instagram.com/identidadrh/"><img src="images/ins.png" class="img"></a> <a HREF="https://www.facebook.com/identidadrh"><img src="images/fb.png" class="img"></A> <a HREF="https://twitter.com/IdentidadRH"><img src="images/tw.png" class="img"></A> <a href="https://www.linkedin.com/company/3501860?trk=tyah&trkInfo=idx%3A1-1-1%2CtarId%3A1423497567513%2Ctas%3Aidentidad+rh "><img src="images/link.png" class="img"></a> </div> <div class="col-md-4 footer-grid wow bounceIn" data-wow-delay="0.4s"> <h3>¿Cómo lo logramos?</h3> <img src="images/c4.jpg" alt=""/> <p>Realizamos un diagnóstico de la imagen de la empresa tanto interno como externo. </p> <p>Diseñamos un plan de marca interno y externo como empleador.</p> <div class="ftr-bwn"> <a href="about.php">Leer Mas</a> </div> </div> <div class="col-md-4 footer-grid wow bounceIn" data-wow-delay="0.4s"> <h3> Identidad RH SRL</h3> <ul class="ftr-list"> <li><a href="about.php">Quienes Somos?</a></li> <li><a href="contact.php">Contacto.</a></li> <li><a href="service.php">Servicios</a></li> <li><a href="#">Expo Empleo</a></li> <li><a href="english.php">English 4 a Career</a></li> </ul> </div> <div class="clearfix"> </div> </div> </div> </div> <!--footer end here-->
Acostangel/expoempleo
Pasantia/includes/footer.php
PHP
gpl-2.0
1,971
secu_loader.elf: file format elf32-littlearm Disassembly of section .text: 00000000 <_reset>: # (7) bootrom jump to 0x0 at last # #================================================= _reset: b _start @ Reset Vector 0: ea00000c b 38 <_start> 1: b 1b 4: eafffffe b 4 <text_start+0x4> 1: b 1b 8: eafffffe b 8 <text_start+0x8> 1: b 1b c: eafffffe b c <text_start+0xc> 1: b 1b 10: eafffffe b 10 <USR_MODE> 1: b 1b 14: eafffffe b 14 <SVC_MODE+0x1> 1: b 1b 18: eafffffe b 18 <ABT_MODE+0x1> 1: b 1b 1c: eafffffe b 1c <UND_MODE+0x1> 00000020 <DATA_IMG_START>: 20: 00000ea4 andeq r0, r0, r4, lsr #29 00000024 <DATA_SEC_START>: 24: 00000ea4 andeq r0, r0, r4, lsr #29 00000028 <DATA_SEC_END>: 28: 00000ea8 andeq r0, r0, r8, lsr #29 0000002c <BSS_SEC_START>: 2c: 00000ea8 andeq r0, r0, r8, lsr #29 00000030 <BSS_SEC_END>: 30: 00000eb4 streqh r0, [r0], -r4 00000034 <STACK_BASE>: 34: 00000eb4 streqh r0, [r0], -r4 00000038 <_start>: #const from Link Scrips DATA_IMG_START: .word data_img_start DATA_SEC_START: .word data_start DATA_SEC_END : .word data_end BSS_SEC_START : .word bss_start BSS_SEC_END : .word bss_end #sys const STACK_BASE : .word bss_end SYSTEM_STACK_SIZE = (1024 * 8) IRQ_STACK_SIZE = 4096 FIQ_STACK_SIZE = 4096 MODE_MASK = 0x1f USR_MODE = 0x10 FIQ_MODE = 0x11 IRQ_MODE = 0x12 SVC_MODE = 0x13 ABT_MODE = 0x17 UND_MODE = 0x1b SYS_MODE = 0x1f IRQ_MASK = 0x80 FIQ_MASK = 0x40 .global _start _start: #============================================================= # Enable ICache #============================================================= mrc p15, 0, r0, c1, c0, 0 38: ee110f10 mrc 15, 0, r0, cr1, cr0, {0} orr r0, r0, #0x00001000 3c: e3800a01 orr r0, r0, #4096 ; 0x1000 # Enable DCache #orr r0, r0, #0x00000100 mcr p15, 0, r0, c1, c0, 0 40: ee010f10 mcr 15, 0, r0, cr1, cr0, {0} #============================================ #Initial DATA Section #============================================ #0.0 Initial ldr r8, DATA_IMG_START 44: e51f802c ldr r8, [pc, #-44] ; 20 <DATA_IMG_START> ldr r9, DATA_SEC_START 48: e51f902c ldr r9, [pc, #-44] ; 24 <DATA_SEC_START> ldr r10, DATA_SEC_END 4c: e51fa02c ldr sl, [pc, #-44] ; 28 <DATA_SEC_END> ldr r11, BSS_SEC_START 50: e51fb02c ldr fp, [pc, #-44] ; 2c <BSS_SEC_START> ldr r12, BSS_SEC_END 54: e51fc02c ldr ip, [pc, #-44] ; 30 <BSS_SEC_END> #1.0 BSS Clear 1: mov r0, #0 58: e3a00000 mov r0, #0 ; 0x0 str r0, [r11], #4 5c: e48b0004 str r0, [fp], #4 cmp r11, r12 60: e15b000c cmp fp, ip bcc 1b 64: 3afffffb bcc 58 <FIQ_MASK+0x18> # *************************************************** # Initialize the system stack pointers for C Main # *************************************************** MRS r1, CPSR @ pick up current PSR 68: e10f1000 mrs r1, CPSR BIC r1, r1, #MODE_MASK @ clear the mode bits 6c: e3c1101f bic r1, r1, #31 ; 0x1f ORR r1, r1, #SVC_MODE @ set the SVC mode bits 70: e3811013 orr r1, r1, #19 ; 0x13 MSR CPSR, r1 @ setup the new CPSR 74: e129f001 msr CPSR_fc, r1 ldr r1, STACK_BASE 78: e51f104c ldr r1, [pc, #-76] ; 34 <STACK_BASE> MOV r2, #SYSTEM_STACK_SIZE 7c: e3a02a02 mov r2, #8192 ; 0x2000 SUB r2, r2, #4 @subtract one word for first addr 80: e2422004 sub r2, r2, #4 ; 0x4 ADD r3, r1, r2 @build start of system stack area 84: e0813002 add r3, r1, r2 BIC r3, r3, #3 @ensure 4-byte aligned 88: e3c33003 bic r3, r3, #3 ; 0x3 MOV sp, r3 8c: e1a0d003 mov sp, r3 mov r0, #0x00000000 @clear r0-r12, lr 90: e3a00000 mov r0, #0 ; 0x0 orr r1, r0, r0 @for clean simulation 94: e1801000 orr r1, r0, r0 stmfd sp!, {r0-r1} 98: e92d0003 stmdb sp!, {r0, r1} ldmfd sp!, {r2-r3} 9c: e8bd000c ldmia sp!, {r2, r3} stmfd sp!, {r0-r3} a0: e92d000f stmdb sp!, {r0, r1, r2, r3} ldmfd sp!, {r4-r7} a4: e8bd00f0 ldmia sp!, {r4, r5, r6, r7} stmfd sp!, {r0-r7} a8: e92d00ff stmdb sp!, {r0, r1, r2, r3, r4, r5, r6, r7} ldmfd sp!, {r6-r12, lr} ac: e8bd5fc0 ldmia sp!, {r6, r7, r8, r9, sl, fp, ip, lr} #============================================ # Jump into the C Main Function # (1) if Do not Need to do Secu Check or # Secu Check Passed, # C main will do the first 4K Sys Boot Code # Copy # (2) if Secu Check Failed main will never return #============================================ bl main b0: eb000001 bl bc <main> 000000b4 <_copy_end>: _copy_end: #================================================ # Start the Sys U-Boot Image from DDR Region at 0x02000000 #================================================ mov r0, #0x02000000 b4: e3a00402 mov r0, #33554432 ; 0x2000000 # blx r0 mov pc, r0 b8: e1a0f000 mov pc, r0 000000bc <main>: int main( int argc, char *argv[] ) { bc: e52de004 str lr, [sp, #-4]! int rt = 0; /* 1. Initial DDR*/ InitDDR(); c0: eb0000b8 bl 3a8 <InitDDR> #if 0 TestDDR(); /* 2. Initial Display and Set Back Ground */ /* 3. Display the Context of DDR at 0x02000000 to Gfx Layer*/ { unsigned int ImgStartAddr = 0; unsigned int ImgWidth = 0; unsigned int ImgHeight = 0; unsigned int ImgFormat = 0; GfxDispImg ( ImgStartAddr = 0x02000000, ImgWidth = 512, ImgHeight = 320, ImgFormat = GFX_CF_RGB565 ); } #endif /* 4. Copy the U-BOOT Region*/ SysImgCopyToDDR(); c4: eb0000f9 bl 4b0 <SysImgCopyToDDR> /* 5. Set BackGround to Blue*/ /* DispSetBackGround(0x0, 0xFF, 0x0); */ return 1; } c8: e3a00001 mov r0, #1 ; 0x1 cc: e49df004 ldr pc, [sp], #4 000000d0 <HWReadInt>: #endif int HWReadInt (unsigned int addr, unsigned int *value) { *value = HW_REG_READ(addr); d0: e5903000 ldr r3, [r0] d4: e5813000 str r3, [r1] return 1; } d8: e3a00001 mov r0, #1 ; 0x1 dc: e1a0f00e mov pc, lr 000000e0 <HWWriteInt>: int HWWriteInt (unsigned int addr, unsigned int value) { #ifdef TRACE_REG_LOG if (fpReg == NULL) { fpReg = fopen("reg.log", "w+"); } if (fpReg != NULL) { fprintf(fpReg, "REG_WRITE: ADDR(%08x) , Data (%08x)\n", addr, value); fflush(fpReg); } #endif HW_REG_WRITE(addr, value); e0: e5801000 str r1, [r0] return 1; } e4: e3a00001 mov r0, #1 ; 0x1 e8: e1a0f00e mov pc, lr 000000ec <HWWriteShort>: int HWWriteShort(unsigned int addr, unsigned short value) { ec: e1a01801 mov r1, r1, lsl #16 f0: e1a01821 mov r1, r1, lsr #16 *(volatile unsigned short*)(addr) = (value); f4: e1c010b0 strh r1, [r0] return 1; } f8: e3a00001 mov r0, #1 ; 0x1 fc: e1a0f00e mov pc, lr 00000100 <HWReadShort>: int HWReadShort (unsigned int addr, unsigned short *value) { (*value) = *(volatile unsigned short*)(addr); 100: e1d030b0 ldrh r3, [r0] 104: e1c130b0 strh r3, [r1] return 1; } 108: e3a00001 mov r0, #1 ; 0x1 10c: e1a0f00e mov pc, lr 00000110 <HWWriteByte>: int HWWriteByte (unsigned int addr, unsigned char value) { 110: e20110ff and r1, r1, #255 ; 0xff #ifdef TRACE_REG_LOG if (fpReg == NULL) { fpReg = fopen("reg.log", "w+"); } if (fpReg != NULL) { fprintf(fpReg, "REG_WRITE: ADDR(%08x) , Data (%08x)\n", addr, value); fflush(fpReg); } #endif *(volatile unsigned char*)(addr) = (value); 114: e5c01000 strb r1, [r0] return 1; } 118: e3a00001 mov r0, #1 ; 0x1 11c: e1a0f00e mov pc, lr 00000120 <HWReadByte>: int HWReadByte (unsigned int addr, unsigned char *value) { (*value) = *(volatile unsigned char*)(addr); 120: e5d03000 ldrb r3, [r0] 124: e5c13000 strb r3, [r1] return 1; } 128: e3a00001 mov r0, #1 ; 0x1 12c: e1a0f00e mov pc, lr 00000130 <RegRead>: //Register and System Memory Interface unsigned int RegRead (unsigned int RegAddr) { 130: e52de004 str lr, [sp, #-4]! 134: e24dd004 sub sp, sp, #4 ; 0x4 unsigned int ReadData = 0; 138: e28d1004 add r1, sp, #4 ; 0x4 13c: e3a03000 mov r3, #0 ; 0x0 140: e5213004 str r3, [r1, #-4]! int rt = 0; rt = HWReadInt(RegAddr,&ReadData); 144: ebffffe1 bl d0 <HWReadInt> return ReadData; } 148: e59d0000 ldr r0, [sp] 14c: e28dd004 add sp, sp, #4 ; 0x4 150: e8bd8000 ldmia sp!, {pc} 00000154 <RegWrite>: void RegWrite (unsigned int RegAddr, unsigned int RegValue) { 154: e52de004 str lr, [sp, #-4]! int rt = 0; rt = HWWriteInt(RegAddr,RegValue); 158: ebffffe0 bl e0 <HWWriteInt> } 15c: e49df004 ldr pc, [sp], #4 00000160 <RegWriteCheck>: int RegWriteCheck(unsigned int RegAddr, unsigned int RegValue) { 160: e92d4070 stmdb sp!, {r4, r5, r6, lr} 164: e24dd004 sub sp, sp, #4 ; 0x4 168: e1a04000 mov r4, r0 16c: e1a05001 mov r5, r1 int rt = 0; 170: e3a02000 mov r2, #0 ; 0x0 unsigned int ReadData = 0; 174: e1a06002 mov r6, r2 178: e58d2000 str r2, [sp] rt = HWWriteInt(RegAddr,RegValue); 17c: ebffffd7 bl e0 <HWWriteInt> rt = HWReadInt(RegAddr,&ReadData); 180: e1a00004 mov r0, r4 184: e1a0100d mov r1, sp 188: ebffffd0 bl d0 <HWReadInt> if ((ReadData) != (RegValue)) 18c: e59d3000 ldr r3, [sp] 190: e1530005 cmp r3, r5 { assert(0); //printf("##ERROR, RegWriteCheck: RegAddr(%08x), WriteValue(%08x), ReadValue(%08x)\n", // RegAddr, RegValue, ReadData); return 0; } return rt; 194: 01a00000 moveq r0, r0 198: 0a000005 beq 1b4 <RegWriteCheck+0x54> 19c: e1a00006 mov r0, r6 1a0: e59f1014 ldr r1, [pc, #20] ; 1bc <.text+0x1bc> 1a4: e1a02006 mov r2, r6 1a8: e3a0306c mov r3, #108 ; 0x6c 1ac: eb0002fd bl da8 <x_assert> 1b0: e1a00006 mov r0, r6 } 1b4: e28dd004 add sp, sp, #4 ; 0x4 1b8: e8bd8070 ldmia sp!, {r4, r5, r6, pc} 1bc: 00000ddc ldreqd r0, [r0], -ip 000001c0 <HWDelay>: void HWDelay(int cnt) { int i = 0; 1c0: e3a03000 mov r3, #0 ; 0x0 int sum = 0; for (i = 0;i < cnt; i++ ) 1c4: e1530000 cmp r3, r0 1c8: a1a0f00e movge pc, lr 1cc: e2833001 add r3, r3, #1 ; 0x1 1d0: e1530000 cmp r3, r0 1d4: bafffffc blt 1cc <HWDelay+0xc> 1d8: e1a0f00e mov pc, lr 000001dc <SetTVEncoderClk>: #endif int SetTVEncoderClk(int IsHD, int IsProgressive) { 1dc: e92d4030 stmdb sp!, {r4, r5, lr} 1e0: e24dd004 sub sp, sp, #4 ; 0x4 1e4: e1a04000 mov r4, r0 1e8: e1a05001 mov r5, r1 U16 FreqCtlValue = 0; 1ec: e28d1004 add r1, sp, #4 ; 0x4 1f0: e3a03000 mov r3, #0 ; 0x0 1f4: e16130b2 strh r3, [r1, #-2]! U16 TVEPLLValue = 0; HWReadShort(REG_CLK_FREQ_CTRL, &FreqCtlValue); 1f8: e59f00d4 ldr r0, [pc, #212] ; 2d4 <.text+0x2d4> 1fc: ebffffbf bl 100 <HWReadShort> FreqCtlValue &= (~(1 << 3)); //Disable the TVE Clock 200: e1dd30b2 ldrh r3, [sp, #2] 204: e3c33008 bic r3, r3, #8 ; 0x8 208: e1cd30b2 strh r3, [sp, #2] HWWriteShort(REG_CLK_FREQ_CTRL, FreqCtlValue); 20c: e59f00c0 ldr r0, [pc, #192] ; 2d4 <.text+0x2d4> 210: e1dd10b2 ldrh r1, [sp, #2] 214: ebffffb4 bl ec <HWWriteShort> //Delay for A while HWDelay(1024); 218: e3a00b01 mov r0, #1024 ; 0x400 21c: ebffffe7 bl 1c0 <HWDelay> //Set TVE clk pll value if (IsHD) { TVEPLLValue = 0x4621; } else { TVEPLLValue = 0x8618; } HWWriteShort(IDS_PCTL_LO, TVEPLLValue); 220: e59f00b0 ldr r0, [pc, #176] ; 2d8 <.text+0x2d8> 224: e59f30b0 ldr r3, [pc, #176] ; 2dc <.text+0x2dc> 228: e59f10b0 ldr r1, [pc, #176] ; 2e0 <.text+0x2e0> 22c: e3540000 cmp r4, #0 ; 0x0 230: 01a01003 moveq r1, r3 234: ebffffac bl ec <HWWriteShort> //Delay for A while HWDelay(1024); 238: e3a00b01 mov r0, #1024 ; 0x400 23c: ebffffdf bl 1c0 <HWDelay> //Enable the TVE Clk FreqCtlValue |= (1 << 3); 240: e1dd30b2 ldrh r3, [sp, #2] 244: e3833008 orr r3, r3, #8 ; 0x8 248: e1cd30b2 strh r3, [sp, #2] //Set TVE_CLK6 switch: FreqCtlValue &= (~( 0x3 << 4)); 24c: e1dd30b2 ldrh r3, [sp, #2] 250: e3c33030 bic r3, r3, #48 ; 0x30 254: e1cd30b2 strh r3, [sp, #2] if (!IsHD && IsProgressive) 258: e2743001 rsbs r3, r4, #1 ; 0x1 25c: 33a03000 movcc r3, #0 ; 0x0 260: e3550000 cmp r5, #0 ; 0x0 264: 03a03000 moveq r3, #0 ; 0x0 268: e3530000 cmp r3, #0 ; 0x0 { FreqCtlValue |= (0x2 << 4); 26c: 11dd30b2 ldrneh r3, [sp, #2] 270: 13833020 orrne r3, r3, #32 ; 0x20 274: 11cd30b2 strneh r3, [sp, #2] } else { FreqCtlValue |= (0x1 << 4); 278: 01dd30b2 ldreqh r3, [sp, #2] 27c: 03833010 orreq r3, r3, #16 ; 0x10 280: 01cd30b2 streqh r3, [sp, #2] } HWWriteShort(REG_CLK_FREQ_CTRL, FreqCtlValue); 284: e59f0048 ldr r0, [pc, #72] ; 2d4 <.text+0x2d4> 288: e1dd10b2 ldrh r1, [sp, #2] 28c: ebffff96 bl ec <HWWriteShort> //Read Back to Check { U16 ReadValue = 0; 290: e3a04000 mov r4, #0 ; 0x0 294: e1cd40b0 strh r4, [sp] HWReadShort( REG_CLK_FREQ_CTRL,&ReadValue); 298: e59f0034 ldr r0, [pc, #52] ; 2d4 <.text+0x2d4> 29c: e1a0100d mov r1, sp 2a0: ebffff96 bl 100 <HWReadShort> assert(FreqCtlValue == ReadValue); 2a4: e1dd30b2 ldrh r3, [sp, #2] 2a8: e1dd00b0 ldrh r0, [sp] 2ac: e1530000 cmp r3, r0 2b0: 13a00000 movne r0, #0 ; 0x0 2b4: 03a00001 moveq r0, #1 ; 0x1 2b8: e59f1024 ldr r1, [pc, #36] ; 2e4 <.text+0x2e4> 2bc: e1a02004 mov r2, r4 2c0: e3a0307c mov r3, #124 ; 0x7c 2c4: eb0002b7 bl da8 <x_assert> } //For Test //Enable CCIR 656 Clk return 1; } 2c8: e3a00001 mov r0, #1 ; 0x1 2cc: e28dd004 add sp, sp, #4 ; 0x4 2d0: e8bd8030 ldmia sp!, {r4, r5, pc} 2d4: 10171108 andnes r1, r7, r8, lsl #2 2d8: 1017140c andnes r1, r7, ip, lsl #8 2dc: 00008618 andeq r8, r0, r8, lsl r6 2e0: 00004621 andeq r4, r0, r1, lsr #12 2e4: 00000de0 andeq r0, r0, r0, ror #27 000002e8 <SetVideoDACMux>: int SetVideoDACMux(int IsYPbPr) { 2e8: e92d4030 stmdb sp!, {r4, r5, lr} 2ec: e24dd004 sub sp, sp, #4 ; 0x4 2f0: e1a05000 mov r5, r0 U16 RegValue = 0; 2f4: e28d1004 add r1, sp, #4 ; 0x4 2f8: e3a03000 mov r3, #0 ; 0x0 2fc: e16130b2 strh r3, [r1, #-2]! HWReadShort(REG_CLK_OPROC_CTRL, &RegValue); 300: e59f0094 ldr r0, [pc, #148] ; 39c <.text+0x39c> 304: ebffff7d bl 100 <HWReadShort> if (IsYPbPr) //Bit0 Dac0 Dac1 Dac2 308: e3550000 cmp r5, #0 ; 0x0 { RegValue |= 0x1; //1 Y Pb Pr 30c: 11dd30b2 ldrneh r3, [sp, #2] 310: 13833001 orrne r3, r3, #1 ; 0x1 314: 11cd30b2 strneh r3, [sp, #2] } else { RegValue |= 0x0; //0 CVBS S-Y S-C } HWWriteShort(REG_CLK_OPROC_CTRL, RegValue); 318: e28d4004 add r4, sp, #4 ; 0x4 31c: e59f0078 ldr r0, [pc, #120] ; 39c <.text+0x39c> 320: e17410b2 ldrh r1, [r4, #-2]! 324: ebffff70 bl ec <HWWriteShort> //Check Register Write HWReadShort(REG_CLK_OPROC_CTRL, &RegValue); 328: e59f006c ldr r0, [pc, #108] ; 39c <.text+0x39c> 32c: e1a01004 mov r1, r4 330: ebffff72 bl 100 <HWReadShort> if (IsYPbPr) //Bit0 Dac0 Dac1 Dac2 334: e3550000 cmp r5, #0 ; 0x0 338: 0a000009 beq 364 <SetVideoDACMux+0x7c> { if ((RegValue & 0x1) != 1) //1 Y Pb Pr 33c: e1dd00b2 ldrh r0, [sp, #2] 340: e3100001 tst r0, #1 ; 0x1 344: 1a000011 bne 390 <SetVideoDACMux+0xa8> { assert(((RegValue & 0x1) == 1)); 348: e2000001 and r0, r0, #1 ; 0x1 34c: e59f104c ldr r1, [pc, #76] ; 3a0 <.text+0x3a0> 350: e3a02000 mov r2, #0 ; 0x0 354: e3a03098 mov r3, #152 ; 0x98 358: eb000292 bl da8 <x_assert> return 0; 35c: e3a00000 mov r0, #0 ; 0x0 360: ea00000b b 394 <SetVideoDACMux+0xac> } } else { if ((RegValue & 0x1) != 0) //1 Y Pb Pr 364: e1dd00b2 ldrh r0, [sp, #2] 368: e3100001 tst r0, #1 ; 0x1 36c: 0a000007 beq 390 <SetVideoDACMux+0xa8> { assert(((RegValue & 0x1) == 0)); 370: e2200001 eor r0, r0, #1 ; 0x1 374: e2000001 and r0, r0, #1 ; 0x1 378: e59f1024 ldr r1, [pc, #36] ; 3a4 <.text+0x3a4> 37c: e3a02000 mov r2, #0 ; 0x0 380: e3a030a0 mov r3, #160 ; 0xa0 384: eb000287 bl da8 <x_assert> return 0; 388: e3a00000 mov r0, #0 ; 0x0 38c: ea000000 b 394 <SetVideoDACMux+0xac> } } return 1; 390: e3a00001 mov r0, #1 ; 0x1 } 394: e28dd004 add sp, sp, #4 ; 0x4 398: e8bd8030 ldmia sp!, {r4, r5, pc} 39c: 10171400 andnes r1, r7, r0, lsl #8 3a0: 00000dfc streqd r0, [r0], -ip 3a4: 00000e14 andeq r0, r0, r4, lsl lr 000003a8 <InitDDR>: int InitDDR() { HW_REG_WRITE(0x10171100,DDR_PLL); 3a8: e59f2040 ldr r2, [pc, #64] ; 3f0 <.text+0x3f0> 3ac: e59f3040 ldr r3, [pc, #64] ; 3f4 <.text+0x3f4> 3b0: e5832000 str r2, [r3] HW_REG_WRITE(0x10110000,DDR_TIMING); 3b4: e59f203c ldr r2, [pc, #60] ; 3f8 <.text+0x3f8> 3b8: e59f303c ldr r3, [pc, #60] ; 3fc <.text+0x3fc> 3bc: e5832000 str r2, [r3] HW_REG_WRITE(0x10110004,DDR_MOD); 3c0: e59f2038 ldr r2, [pc, #56] ; 400 <.text+0x400> 3c4: e2833004 add r3, r3, #4 ; 0x4 3c8: e5832000 str r2, [r3] HW_REG_WRITE(0x10110008,DDR_DELAY_0); 3cc: e59f2030 ldr r2, [pc, #48] ; 404 <.text+0x404> 3d0: e2833004 add r3, r3, #4 ; 0x4 3d4: e4832004 str r2, [r3], #4 HW_REG_WRITE(0x1011000c,DDR_DELAY_1); 3d8: e5832000 str r2, [r3] HW_REG_WRITE(0x10110010,DDR_MISC); 3dc: e59f2024 ldr r2, [pc, #36] ; 408 <.text+0x408> 3e0: e2833004 add r3, r3, #4 ; 0x4 3e4: e5832000 str r2, [r3] //configuration DDR queue prots to enhance DDR performance to support deinterlace // HW_REG_WRITE(0x1011004c,0x20); // HW_REG_WRITE(0x10110050,0x1); // HW_REG_WRITE(0x10110054,0x0); return 1; } 3e8: e3a00001 mov r0, #1 ; 0x1 3ec: e1a0f00e mov pc, lr 3f0: 0000084f andeq r0, r0, pc, asr #16 3f4: 10171100 andnes r1, r7, r0, lsl #2 3f8: 77369890 undefined 3fc: 10110000 andnes r0, r1, r0 400: 93410225 cmpls r1, #1342177282 ; 0x50000002 404: 08080808 stmeqda r8, {r3, fp} 408: 30100465 andccs r0, r0, r5, ror #8 0000040c <TestDDR>: int TestDDR() { 40c: e92d4010 stmdb sp!, {r4, lr} 410: e24dd018 sub sp, sp, #24 ; 0x18 unsigned int TestData[] = 414: e59f308c ldr r3, [pc, #140] ; 4a8 <.text+0x4a8> 418: e1a0c00d mov ip, sp 41c: e1a0e003 mov lr, r3 420: e8be000f ldmia lr!, {r0, r1, r2, r3} 424: e8ac000f stmia ip!, {r0, r1, r2, r3} 428: e89e0003 ldmia lr, {r0, r1} 42c: e88c0003 stmia ip, {r0, r1} { 0x12345678, 0x9ABCDEF0, 0xAAAAAAAA, 0x55555555, 0x0, 0xFFFFFFFF, }; unsigned int StartAddr = 0x02000000; 430: e3a00402 mov r0, #33554432 ; 0x2000000 int i = 0; int rt = 0; //Write for (i = 0; i < sizeof(TestData)/sizeof(unsigned int); i++) 434: e3a01000 mov r1, #0 ; 0x0 { HW_REG_WRITE(StartAddr + i*4, TestData[i]); 438: e28d2018 add r2, sp, #24 ; 0x18 43c: e0823101 add r3, r2, r1, lsl #2 440: e5133018 ldr r3, [r3, #-24] 444: e7803101 str r3, [r0, r1, lsl #2] 448: e2811001 add r1, r1, #1 ; 0x1 44c: e3510005 cmp r1, #5 ; 0x5 450: 9afffff8 bls 438 <TestDDR+0x2c> } //Check rt = 0; 454: e3a04000 mov r4, #0 ; 0x0 for (i = 0; i < sizeof(TestData)/sizeof(unsigned int); i++) 458: e1a01004 mov r1, r4 { unsigned int ReadData = 0; ReadData = ~TestData[i]; 45c: e28d2018 add r2, sp, #24 ; 0x18 460: e0823101 add r3, r2, r1, lsl #2 464: e5132018 ldr r2, [r3, #-24] ReadData = HW_REG_READ(StartAddr + i*4); 468: e7903101 ldr r3, [r0, r1, lsl #2] if(ReadData != TestData[i]) 46c: e1520003 cmp r2, r3 rt++; 470: 12844001 addne r4, r4, #1 ; 0x1 474: e2811001 add r1, r1, #1 ; 0x1 478: e3510005 cmp r1, #5 ; 0x5 47c: 9afffff6 bls 45c <TestDDR+0x50> } assert(rt == 0); 480: e2740001 rsbs r0, r4, #1 ; 0x1 484: 33a00000 movcc r0, #0 ; 0x0 488: e59f101c ldr r1, [pc, #28] ; 4ac <.text+0x4ac> 48c: e3a02000 mov r2, #0 ; 0x0 490: e3a030b5 mov r3, #181 ; 0xb5 494: eb000243 bl da8 <x_assert> return !rt; } 498: e2740001 rsbs r0, r4, #1 ; 0x1 49c: 33a00000 movcc r0, #0 ; 0x0 4a0: e28dd018 add sp, sp, #24 ; 0x18 4a4: e8bd8010 ldmia sp!, {r4, pc} 4a8: 00000dc4 andeq r0, r0, r4, asr #27 4ac: 00000e2c andeq r0, r0, ip, lsr #28 000004b0 <SysImgCopyToDDR>: #include "secu_hw_if.h" #include "../stdlib/c_stdlib.h" int SysImgCopyToDDR(void) { 4b0: e92d40f0 stmdb sp!, {r4, r5, r6, r7, lr} int i; int ret = 0; unsigned char *DDRBuf = NULL; SecHWImgOpen(); 4b4: eb000036 bl 594 <SecHWImgOpen> DDRBuf = (unsigned char *)APP_IMG_COPY_DDR_ADDR; 4b8: e3a07402 mov r7, #33554432 ; 0x2000000 for(i = 0; i < APP_IMG_COPY_SIZE/1024; i++) { 4bc: e3a04000 mov r4, #0 ; 0x0 4c0: e59f6050 ldr r6, [pc, #80] ; 518 <.text+0x518> ret = SecHWImgRead(APP_IMG_START + (i << 10), 1024 , DDRBuf + (i << 10)); 4c4: e1a02504 mov r2, r4, lsl #10 4c8: e2820b05 add r0, r2, #5120 ; 0x1400 4cc: e3a01b01 mov r1, #1024 ; 0x400 4d0: e0822007 add r2, r2, r7 4d4: eb000046 bl 5f4 <SecHWImgRead> 4d8: e1a05000 mov r5, r0 assert(ret == 1024); 4dc: e3500b01 cmp r0, #1024 ; 0x400 4e0: 13a00000 movne r0, #0 ; 0x0 4e4: 03a00001 moveq r0, #1 ; 0x1 4e8: e59f102c ldr r1, [pc, #44] ; 51c <.text+0x51c> 4ec: e3a02000 mov r2, #0 ; 0x0 4f0: e3a03016 mov r3, #22 ; 0x16 4f4: eb00022b bl da8 <x_assert> 4f8: e2844001 add r4, r4, #1 ; 0x1 4fc: e1540006 cmp r4, r6 500: daffffef ble 4c4 <SysImgCopyToDDR+0x14> } SecHWImgClose(); 504: eb00002e bl 5c4 <SecHWImgClose> return ret > 0; } 508: e3550000 cmp r5, #0 ; 0x0 50c: d3a00000 movle r0, #0 ; 0x0 510: c3a00001 movgt r0, #1 ; 0x1 514: e8bd80f0 ldmia sp!, {r4, r5, r6, r7, pc} 518: 0000012b andeq r0, r0, fp, lsr #2 51c: 00000e34 andeq r0, r0, r4, lsr lr 00000520 <SecHWGetBootInfo>: /* Return SMC_STA Value */ unsigned int SecHWGetBootInfo(void) { return REG_READ(SMC_BOOT); 520: e59f3004 ldr r3, [pc, #4] ; 52c <.text+0x52c> 524: e5930000 ldr r0, [r3] } 528: e1a0f00e mov pc, lr 52c: 10100034 andnes r0, r0, r4, lsr r0 00000530 <SecHWGetBootMode>: unsigned int SecHWGetBootMode(void) { unsigned int BootInfo = 0; unsigned int BootMode = 0; BootInfo = REG_READ(SMC_BOOT); 530: e59f301c ldr r3, [pc, #28] ; 554 <.text+0x554> 534: e5933000 ldr r3, [r3] if (BootInfo & 0x1) { 538: e3130001 tst r3, #1 ; 0x1 if (BootInfo & 0x10) { BootMode = SPI_BOOT; #ifdef SPI_NAND_BOOT BootMode = NAND_BOOT; #endif } else { BootMode = NAND_BOOT; } } else { BootMode = NOR_BOOT; 53c: 03a00000 moveq r0, #0 ; 0x0 540: 01a0f00e moveq pc, lr 544: e3130010 tst r3, #16 ; 0x10 548: 03a00001 moveq r0, #1 ; 0x1 54c: 13a00002 movne r0, #2 ; 0x2 550: e1a0f00e mov pc, lr 554: 10100034 andnes r0, r0, r4, lsr r0 00000558 <SecHWIsRSACheckEna>: } #ifdef MANUAL_BOOT_MODE BootMode = MANUAL_BOOT_MODE; #endif return BootMode; } /*Read Secure Config */ int SecHWIsRSACheckEna(void) { unsigned int OTPInfo = 0; OTPInfo = REG_READ(OTP_CFG); 558: e59f3010 ldr r3, [pc, #16] ; 570 <.text+0x570> 55c: e5930000 ldr r0, [r3] return (((OTPInfo >> OTP_SEC_BOOT_BIT) & 0x1) == RSA_CHECK_ENA); 560: e1a001a0 mov r0, r0, lsr #3 564: e2200001 eor r0, r0, #1 ; 0x1 } 568: e2000001 and r0, r0, #1 ; 0x1 56c: e1a0f00e mov pc, lr 570: fffff828 swinv 0x00fff828 00000574 <SecHWGetKeyAddr>: unsigned char *SecHWGetKeyAddr(void) { unsigned int OTPInfo = 0; OTPInfo = REG_READ(OTP_CFG); 574: e59f3014 ldr r3, [pc, #20] ; 590 <.text+0x590> 578: e5930000 ldr r0, [r3] OTPInfo = (OTPInfo >> OTP_KEY_INDEX_BIT) & 0x7; 57c: e1a00820 mov r0, r0, lsr #16 580: e2000007 and r0, r0, #7 ; 0x7 return (unsigned char *)(PUB_KEY_START + 256 * OTPInfo); 584: e1a00400 mov r0, r0, lsl #8 } 588: e2400b12 sub r0, r0, #18432 ; 0x4800 58c: e1a0f00e mov pc, lr 590: fffff828 swinv 0x00fff828 00000594 <SecHWImgOpen>: int SecHWImgOpen(void) { 594: e52de004 str lr, [sp, #-4]! int ret = 0; unsigned int BootMode = 0; BootMode = SecHWGetBootMode(); 598: ebffffe4 bl 530 <SecHWGetBootMode> if (BootMode == SPI_BOOT) { 59c: e3500002 cmp r0, #2 ; 0x2 5a0: 1a000001 bne 5ac <SecHWImgOpen+0x18> ret = SPIOpen(); 5a4: eb000150 bl aec <SPIOpen> 5a8: e49df004 ldr pc, [sp], #4 } else if (BootMode == NAND_BOOT) { 5ac: e3500001 cmp r0, #1 ; 0x1 5b0: 1a000001 bne 5bc <SecHWImgOpen+0x28> ret = NANDOpen(); 5b4: eb0000a0 bl 83c <NANDOpen> 5b8: e49df004 ldr pc, [sp], #4 } else { ret = NOROpen(); 5bc: eb000059 bl 728 <NOROpen> } return ret; } 5c0: e49df004 ldr pc, [sp], #4 000005c4 <SecHWImgClose>: int SecHWImgClose(void) { 5c4: e52de004 str lr, [sp, #-4]! int ret = 0; unsigned int BootMode = 0; BootMode = SecHWGetBootMode(); 5c8: ebffffd8 bl 530 <SecHWGetBootMode> if (BootMode == SPI_BOOT) { 5cc: e3500002 cmp r0, #2 ; 0x2 5d0: 1a000001 bne 5dc <SecHWImgClose+0x18> ret = SPIClose(); 5d4: eb00014c bl b0c <SPIClose> 5d8: e49df004 ldr pc, [sp], #4 } else if (BootMode == NAND_BOOT) { 5dc: e3500001 cmp r0, #1 ; 0x1 5e0: 1a000001 bne 5ec <SecHWImgClose+0x28> ret = NANDClose(); 5e4: eb00013e bl ae4 <NANDClose> 5e8: e49df004 ldr pc, [sp], #4 } else { ret = NORClose(); 5ec: eb000086 bl 80c <NORClose> } return ret; } 5f0: e49df004 ldr pc, [sp], #4 000005f4 <SecHWImgRead>: int SecHWImgRead(unsigned int StartAddr, int Size, unsigned char *Buf) { 5f4: e92d40f0 stmdb sp!, {r4, r5, r6, r7, lr} 5f8: e24ddb01 sub sp, sp, #1024 ; 0x400 5fc: e1a05000 mov r5, r0 600: e1a07002 mov r7, r2 int ret = 0; unsigned int BootMode = 0; unsigned int direct_copy; unsigned char buffer[1024]; if(Size <= 0) 604: e2516000 subs r6, r1, #0 ; 0x0 return Size; 608: d1a00006 movle r0, r6 60c: da000042 ble 71c <SecHWImgRead+0x128> /* cross 1K boundary not allowed! */ assert((StartAddr & (~0x3ff)) == ((StartAddr + Size - 1) & ~0x3ff)); 610: e3c53fff bic r3, r5, #1020 ; 0x3fc 614: e3c33003 bic r3, r3, #3 ; 0x3 618: e0850006 add r0, r5, r6 61c: e2400001 sub r0, r0, #1 ; 0x1 620: e3c00fff bic r0, r0, #1020 ; 0x3fc 624: e3c00003 bic r0, r0, #3 ; 0x3 628: e1530000 cmp r3, r0 62c: 13a00000 movne r0, #0 ; 0x0 630: 03a00001 moveq r0, #1 ; 0x1 634: e59f10e8 ldr r1, [pc, #232] ; 724 <.text+0x724> 638: e3a02000 mov r2, #0 ; 0x0 63c: e3a0307b mov r3, #123 ; 0x7b 640: eb0001d8 bl da8 <x_assert> direct_copy = ((StartAddr & 0x3ff) == 0) && (Size == 1024); 644: e1a04b05 mov r4, r5, lsl #22 648: e1a04b24 mov r4, r4, lsr #22 64c: e3540000 cmp r4, #0 ; 0x0 650: 03560b01 cmpeq r6, #1024 ; 0x400 654: 13a04000 movne r4, #0 ; 0x0 658: 03a04001 moveq r4, #1 ; 0x1 BootMode = SecHWGetBootMode(); 65c: ebffffb3 bl 530 <SecHWGetBootMode> if (BootMode == SPI_BOOT) { 660: e3500002 cmp r0, #2 ; 0x2 664: 1a00000a bne 694 <SecHWImgRead+0xa0> if(direct_copy) 668: e3540000 cmp r4, #0 ; 0x0 66c: 0a000003 beq 680 <SecHWImgRead+0x8c> ret = SPIRead_1K(StartAddr, Buf); 670: e1a00005 mov r0, r5 674: e1a01007 mov r1, r7 678: eb00011f bl afc <SPIRead_1K> 67c: ea00001d b 6f8 <SecHWImgRead+0x104> else ret = SPIRead_1K(StartAddr & (~0x3ff), &buffer[0]); 680: e3c50fff bic r0, r5, #1020 ; 0x3fc 684: e3c00003 bic r0, r0, #3 ; 0x3 688: e1a0100d mov r1, sp 68c: eb00011a bl afc <SPIRead_1K> 690: ea000018 b 6f8 <SecHWImgRead+0x104> } else if (BootMode == NAND_BOOT) { 694: e3500001 cmp r0, #1 ; 0x1 698: 1a00000a bne 6c8 <SecHWImgRead+0xd4> if(direct_copy) 69c: e3540000 cmp r4, #0 ; 0x0 6a0: 0a000003 beq 6b4 <SecHWImgRead+0xc0> ret = NANDRead_1K(StartAddr, Buf); 6a4: e1a00005 mov r0, r5 6a8: e1a01007 mov r1, r7 6ac: eb000075 bl 888 <NANDRead_1K> 6b0: ea000010 b 6f8 <SecHWImgRead+0x104> else ret = NANDRead_1K(StartAddr & (~0x3ff), &buffer[0]); 6b4: e3c50fff bic r0, r5, #1020 ; 0x3fc 6b8: e3c00003 bic r0, r0, #3 ; 0x3 6bc: e1a0100d mov r1, sp 6c0: eb000070 bl 888 <NANDRead_1K> 6c4: ea00000b b 6f8 <SecHWImgRead+0x104> } else { if(direct_copy) 6c8: e3540000 cmp r4, #0 ; 0x0 6cc: 0a000004 beq 6e4 <SecHWImgRead+0xf0> ret = NORRead(StartAddr, 1024, Buf); 6d0: e1a00005 mov r0, r5 6d4: e3a01b01 mov r1, #1024 ; 0x400 6d8: e1a02007 mov r2, r7 6dc: eb000013 bl 730 <NORRead> 6e0: ea000004 b 6f8 <SecHWImgRead+0x104> else ret = NORRead(StartAddr & (~0x3ff), 1024, &buffer[0]); 6e4: e3c50fff bic r0, r5, #1020 ; 0x3fc 6e8: e3c00003 bic r0, r0, #3 ; 0x3 6ec: e3a01b01 mov r1, #1024 ; 0x400 6f0: e1a0200d mov r2, sp 6f4: eb00000d bl 730 <NORRead> } if(!direct_copy) 6f8: e3540000 cmp r4, #0 ; 0x0 6fc: 1a000005 bne 718 <SecHWImgRead+0x124> memcpy(Buf, &buffer[StartAddr & 0x3ff], Size); 700: e1a01b05 mov r1, r5, lsl #22 704: e1a01b21 mov r1, r1, lsr #22 708: e1a00007 mov r0, r7 70c: e08d1001 add r1, sp, r1 710: e1a02006 mov r2, r6 714: eb000167 bl cb8 <x_memcpy> return Size; 718: e1a00006 mov r0, r6 } 71c: e28ddb01 add sp, sp, #1024 ; 0x400 720: e8bd80f0 ldmia sp!, {r4, r5, r6, r7, pc} 724: 00000e40 andeq r0, r0, r0, asr #28 00000728 <NOROpen>: int NOROpen (void) { return 1; } 728: e3a00001 mov r0, #1 ; 0x1 72c: e1a0f00e mov pc, lr 00000730 <NORRead>: int NORRead(unsigned int StartAddr, int Size, unsigned char *Buf) { 730: e92d4010 stmdb sp!, {r4, lr} int i = 0; 734: e3a04000 mov r4, #0 ; 0x0 unsigned char *Src = 0; Src += (NOR_FLASH_BASE + StartAddr); 738: e280c30d add ip, r0, #872415232 ; 0x34000000 if (( (StartAddr &0x3) == (((unsigned int)Buf) & 0x3)) 73c: e2000003 and r0, r0, #3 ; 0x3 740: e1a0e000 mov lr, r0 744: e2023003 and r3, r2, #3 ; 0x3 748: e1500003 cmp r0, r3 74c: 1a00001c bne 7c4 <NORRead+0x94> 750: e2803004 add r3, r0, #4 ; 0x4 754: e1510003 cmp r1, r3 758: 3a000019 bcc 7c4 <NORRead+0x94> && (Size >= ((StartAddr &0x3 ) + 4) )) { unsigned int *s = 0; unsigned int *d = 0; for (i = 0; i < (StartAddr &0x3); i++) 75c: e1540000 cmp r4, r0 760: 2a000004 bcs 778 <NORRead+0x48> *Buf++ = *Src++; 764: e4dc3001 ldrb r3, [ip], #1 768: e4c23001 strb r3, [r2], #1 76c: e2844001 add r4, r4, #1 ; 0x1 770: e154000e cmp r4, lr 774: 3afffffa bcc 764 <NORRead+0x34> s = (unsigned int*)Src; 778: e1a0000c mov r0, ip d = (unsigned int*)Buf; for (; i < Size; i += 4) 77c: e1540001 cmp r4, r1 780: aa000004 bge 798 <NORRead+0x68> *d++ = *s++; 784: e4903004 ldr r3, [r0], #4 788: e4823004 str r3, [r2], #4 78c: e2844004 add r4, r4, #4 ; 0x4 790: e1540001 cmp r4, r1 794: bafffffa blt 784 <NORRead+0x54> Src = (unsigned char*)(s - 1) + 1; 798: e240c003 sub ip, r0, #3 ; 0x3 Buf = (unsigned char*)(d - 1) + 1; 79c: e2422003 sub r2, r2, #3 ; 0x3 i = (i - 4 + 1); 7a0: e2444003 sub r4, r4, #3 ; 0x3 for (; i < Size; i++) 7a4: e1540001 cmp r4, r1 7a8: aa00000d bge 7e4 <NORRead+0xb4> *Buf++ = *Src++; 7ac: e4dc3001 ldrb r3, [ip], #1 7b0: e4c23001 strb r3, [r2], #1 7b4: e2844001 add r4, r4, #1 ; 0x1 7b8: e1540001 cmp r4, r1 7bc: bafffffa blt 7ac <NORRead+0x7c> 7c0: ea000007 b 7e4 <NORRead+0xb4> } else { for (i = 0; i < Size; i++) 7c4: e3a04000 mov r4, #0 ; 0x0 7c8: e1540001 cmp r4, r1 7cc: aa000004 bge 7e4 <NORRead+0xb4> *Buf++ = *Src++; 7d0: e4dc3001 ldrb r3, [ip], #1 7d4: e4c23001 strb r3, [r2], #1 7d8: e2844001 add r4, r4, #1 ; 0x1 7dc: e1540001 cmp r4, r1 7e0: bafffffa blt 7d0 <NORRead+0xa0> } assert(i == Size); 7e4: e1540001 cmp r4, r1 7e8: 13a00000 movne r0, #0 ; 0x0 7ec: 03a00001 moveq r0, #1 ; 0x1 7f0: e59f1010 ldr r1, [pc, #16] ; 808 <.text+0x808> 7f4: e3a02000 mov r2, #0 ; 0x0 7f8: e3a0302f mov r3, #47 ; 0x2f 7fc: eb000169 bl da8 <x_assert> return i; } 800: e1a00004 mov r0, r4 804: e8bd8010 ldmia sp!, {r4, pc} 808: 00000e7c andeq r0, r0, ip, ror lr 0000080c <NORClose>: int NORClose(void) { return 1; } 80c: e3a00001 mov r0, #1 ; 0x1 810: e1a0f00e mov pc, lr 00000814 <NANDWait>: #ifdef NAND_FUNC_ENA int i; volatile unsigned int *p; p = (volatile unsigned int *)NAND_STA; 814: e59f201c ldr r2, [pc, #28] ; 838 <.text+0x838> do { for(i = 0; i < 20; i++) ; 818: e3a03000 mov r3, #0 ; 0x0 81c: e2833001 add r3, r3, #1 ; 0x1 820: e3530013 cmp r3, #19 ; 0x13 824: dafffffc ble 81c <NANDWait+0x8> } while((*p & 0x1) == 0); 828: e5923000 ldr r3, [r2] 82c: e3130001 tst r3, #1 ; 0x1 830: 0afffff8 beq 818 <NANDWait+0x4> #endif } 834: e1a0f00e mov pc, lr 838: 10100030 andnes r0, r0, r0, lsr r0 0000083c <NANDOpen>: int NANDOpen (void) { 83c: e52de004 str lr, [sp, #-4]! #ifdef NAND_FUNC_ENA unsigned int boot_cfg; volatile unsigned int *p; volatile unsigned short *ps; volatile unsigned char *pc; #if 0 p = (volatile unsigned int *)BOOT_CFG; boot_cfg = *p; large_block = (unsigned char)((boot_cfg >> 1) & 0x1); io_width_16 = (unsigned char)((boot_cfg >> 2) & 0x1); addr_cyc_2 = (unsigned char)((boot_cfg >> 3) & 0x1); #else /* TODO SUNEH: temparary exist for test */ large_block = 1; 840: e3a02001 mov r2, #1 ; 0x1 844: e59f302c ldr r3, [pc, #44] ; 878 <.text+0x878> 848: e5c32000 strb r2, [r3] io_width_16 = 0; 84c: e2422001 sub r2, r2, #1 ; 0x1 850: e59f3024 ldr r3, [pc, #36] ; 87c <.text+0x87c> 854: e5c32000 strb r2, [r3] addr_cyc_2 = 0; 858: e59f3020 ldr r3, [pc, #32] ; 880 <.text+0x880> 85c: e5c32000 strb r2, [r3] #endif if(io_width_16) { ps = (volatile unsigned short *)NAND_CMD; *ps = 0xff; } else { pc = (volatile unsigned char *)NAND_CMD; *pc = 0xff; 860: e2422001 sub r2, r2, #1 ; 0x1 864: e59f3018 ldr r3, [pc, #24] ; 884 <.text+0x884> 868: e5c32000 strb r2, [r3] } NANDWait (); 86c: ebffffe8 bl 814 <NANDWait> #endif return 1; } 870: e3a00001 mov r0, #1 ; 0x1 874: e49df004 ldr pc, [sp], #4 878: 00000ea8 andeq r0, r0, r8, lsr #29 87c: 00000ea9 andeq r0, r0, r9, lsr #29 880: 00000eaa andeq r0, r0, sl, lsr #29 884: 34800002 strcc r0, [r0], #2 00000888 <NANDRead_1K>: int NANDRead_1K(unsigned int StartAddr, unsigned char *Buf) /* Warning: assume 1K alignment for StartAddr */ { 888: e92d41f0 stmdb sp!, {r4, r5, r6, r7, r8, lr} 88c: e1a05000 mov r5, r0 890: e1a04001 mov r4, r1 int i; int j; volatile unsigned short *ps; volatile unsigned char *pc; unsigned char *pBuf = Buf; #ifdef NAND_FUNC_ENA assert((StartAddr & 0x3ff) == 0); 894: e1a00b00 mov r0, r0, lsl #22 898: e1a00b20 mov r0, r0, lsr #22 89c: e2700001 rsbs r0, r0, #1 ; 0x1 8a0: 33a00000 movcc r0, #0 ; 0x0 8a4: e59f121c ldr r1, [pc, #540] ; ac8 <.text+0xac8> 8a8: e3a02000 mov r2, #0 ; 0x0 8ac: e3a03058 mov r3, #88 ; 0x58 8b0: eb00013c bl da8 <x_assert> if(large_block) { 8b4: e59f3210 ldr r3, [pc, #528] ; acc <.text+0xacc> 8b8: e5d33000 ldrb r3, [r3] 8bc: e3530000 cmp r3, #0 ; 0x0 8c0: 0a000040 beq 9c8 <NANDRead_1K+0x140> if(io_width_16) { 8c4: e59f3204 ldr r3, [pc, #516] ; ad0 <.text+0xad0> 8c8: e5d33000 ldrb r3, [r3] 8cc: e3530000 cmp r3, #0 ; 0x0 8d0: 0a00001f beq 954 <NANDRead_1K+0xcc> ps = (volatile unsigned short *)NAND_CMD; 8d4: e59fc1f8 ldr ip, [pc, #504] ; ad4 <.text+0xad4> *ps = 0x00; 8d8: e3a03000 mov r3, #0 ; 0x0 8dc: e1cc30b0 strh r3, [ip] ps = (volatile unsigned short *)NAND_ADDR; 8e0: e28cc002 add ip, ip, #2 ; 0x2 *ps = 0x00; 8e4: e1cc30b0 strh r3, [ip] *ps = (StartAddr >> 9) & 0x03; 8e8: e1a034a5 mov r3, r5, lsr #9 8ec: e2033003 and r3, r3, #3 ; 0x3 8f0: e1cc30b0 strh r3, [ip] *ps = (StartAddr >> 11) & 0xff; 8f4: e1a035a5 mov r3, r5, lsr #11 8f8: e20330ff and r3, r3, #255 ; 0xff 8fc: e1cc30b0 strh r3, [ip] *ps = (StartAddr >> 19) & 0xff; 900: e1a039a5 mov r3, r5, lsr #19 904: e20330ff and r3, r3, #255 ; 0xff 908: e1cc30b0 strh r3, [ip] if(~addr_cyc_2) 90c: e59f31c4 ldr r3, [pc, #452] ; ad8 <.text+0xad8> 910: e5d33000 ldrb r3, [r3] 914: e3730001 cmn r3, #1 ; 0x1 *ps = (StartAddr >> 27) & 0xff; 918: 11a03da5 movne r3, r5, lsr #27 91c: 11cc30b0 strneh r3, [ip] ps = (volatile unsigned short *)NAND_CMD; 920: e59fc1ac ldr ip, [pc, #428] ; ad4 <.text+0xad4> *ps = 0x30; 924: e3a03030 mov r3, #48 ; 0x30 928: e1cc30b0 strh r3, [ip] NANDWait (); 92c: ebffffb8 bl 814 <NANDWait> ps = (volatile unsigned short *)NAND_IO; 930: e3a0c5d2 mov ip, #880803840 ; 0x34800000 for(j = 0; j < 512; j++) { 934: e3a02000 mov r2, #0 ; 0x0 938: e59f119c ldr r1, [pc, #412] ; adc <.text+0xadc> *((unsigned short *)pBuf) = *ps; 93c: e1dc30b0 ldrh r3, [ip] 940: e0c430b2 strh r3, [r4], #2 944: e2822001 add r2, r2, #1 ; 0x1 948: e1520001 cmp r2, r1 94c: dafffffa ble 93c <NANDRead_1K+0xb4> 950: ea00005a b ac0 <NANDRead_1K+0x238> pBuf += 2; } } else { pc = (volatile unsigned char *)NAND_CMD; 954: e59fc178 ldr ip, [pc, #376] ; ad4 <.text+0xad4> *pc = 0x00; 958: e3a03000 mov r3, #0 ; 0x0 95c: e4cc3002 strb r3, [ip], #2 pc = (volatile unsigned char *)NAND_ADDR; *pc = 0x00; 960: e5cc3000 strb r3, [ip] *pc = (StartAddr >> 8) & 0x07; 964: e1a03425 mov r3, r5, lsr #8 968: e2033007 and r3, r3, #7 ; 0x7 96c: e5cc3000 strb r3, [ip] *pc = (StartAddr >> 11) & 0xff; 970: e1a035a5 mov r3, r5, lsr #11 974: e5cc3000 strb r3, [ip] *pc = (StartAddr >> 19) & 0xff; 978: e1a039a5 mov r3, r5, lsr #19 97c: e5cc3000 strb r3, [ip] if(~addr_cyc_2) 980: e59f3150 ldr r3, [pc, #336] ; ad8 <.text+0xad8> 984: e5d33000 ldrb r3, [r3] 988: e3730001 cmn r3, #1 ; 0x1 *pc = (StartAddr >> 27) & 0xff; 98c: 11a03da5 movne r3, r5, lsr #27 990: 15cc3000 strneb r3, [ip] pc = (volatile unsigned char *)NAND_CMD; 994: e59fc138 ldr ip, [pc, #312] ; ad4 <.text+0xad4> *pc = 0x30; 998: e3a03030 mov r3, #48 ; 0x30 99c: e5cc3000 strb r3, [ip] NANDWait (); 9a0: ebffff9b bl 814 <NANDWait> pc = (volatile unsigned char *)NAND_IO; 9a4: e3a0c5d2 mov ip, #880803840 ; 0x34800000 for(j = 0; j < 1024; j++) { 9a8: e3a02000 mov r2, #0 ; 0x0 9ac: e59f112c ldr r1, [pc, #300] ; ae0 <.text+0xae0> *pBuf = *pc; 9b0: e5dc3000 ldrb r3, [ip] 9b4: e4c43001 strb r3, [r4], #1 9b8: e2822001 add r2, r2, #1 ; 0x1 9bc: e1520001 cmp r2, r1 9c0: dafffffa ble 9b0 <NANDRead_1K+0x128> 9c4: ea00003d b ac0 <NANDRead_1K+0x238> pBuf++; } } } else { if(io_width_16) { 9c8: e59f3100 ldr r3, [pc, #256] ; ad0 <.text+0xad0> 9cc: e5d33000 ldrb r3, [r3] 9d0: e3530000 cmp r3, #0 ; 0x0 for(i = 0; i < 4; i++) { ps = (volatile unsigned short *)NAND_CMD; *ps = (i & 0x1); ps = (volatile unsigned short *)NAND_ADDR; *ps = 0x00; *ps = ((StartAddr >> 9) & 0xff) | (i >> 1); *ps = (StartAddr >> 17) & 0xff; if(~addr_cyc_2) *ps = (StartAddr >> 25) & 0xff; NANDWait (); ps = (volatile unsigned short *)NAND_IO; for(j = 0; j < 128; j++) { *((unsigned short *)pBuf) = *ps; pBuf += 2; } } } else { for(i = 0; i < 4; i++) { 9d4: 03a06000 moveq r6, #0 ; 0x0 9d8: 0a00001e beq a58 <NANDRead_1K+0x1d0> 9dc: e3a06000 mov r6, #0 ; 0x0 9e0: e1a034a5 mov r3, r5, lsr #9 9e4: e20370ff and r7, r3, #255 ; 0xff 9e8: e1a038a5 mov r3, r5, lsr #17 9ec: e20380ff and r8, r3, #255 ; 0xff 9f0: e1a05ca5 mov r5, r5, lsr #25 9f4: e59fc0d8 ldr ip, [pc, #216] ; ad4 <.text+0xad4> 9f8: e2063001 and r3, r6, #1 ; 0x1 9fc: e1cc30b0 strh r3, [ip] a00: e28cc002 add ip, ip, #2 ; 0x2 a04: e3a03000 mov r3, #0 ; 0x0 a08: e1cc30b0 strh r3, [ip] a0c: e18730c6 orr r3, r7, r6, asr #1 a10: e1cc30b0 strh r3, [ip] a14: e1cc80b0 strh r8, [ip] a18: e59f30b8 ldr r3, [pc, #184] ; ad8 <.text+0xad8> a1c: e5d33000 ldrb r3, [r3] a20: e3730001 cmn r3, #1 ; 0x1 a24: 11cc50b0 strneh r5, [ip] a28: ebffff79 bl 814 <NANDWait> a2c: e3a0c5d2 mov ip, #880803840 ; 0x34800000 a30: e3a02000 mov r2, #0 ; 0x0 a34: e1dc30b0 ldrh r3, [ip] a38: e0c430b2 strh r3, [r4], #2 a3c: e2822001 add r2, r2, #1 ; 0x1 a40: e352007f cmp r2, #127 ; 0x7f a44: dafffffa ble a34 <NANDRead_1K+0x1ac> a48: e2866001 add r6, r6, #1 ; 0x1 a4c: e3560003 cmp r6, #3 ; 0x3 a50: daffffe7 ble 9f4 <NANDRead_1K+0x16c> a54: ea000019 b ac0 <NANDRead_1K+0x238> pc = (volatile unsigned char *)NAND_CMD; a58: e59fc074 ldr ip, [pc, #116] ; ad4 <.text+0xad4> *pc = (i & 0x1); a5c: e2063001 and r3, r6, #1 ; 0x1 a60: e4cc3002 strb r3, [ip], #2 pc = (volatile unsigned char *)NAND_ADDR; *pc = 0x00; a64: e3a03000 mov r3, #0 ; 0x0 a68: e5cc3000 strb r3, [ip] *pc = ((StartAddr >> 9) & 0xff) | (i >> 1); a6c: e1a030c6 mov r3, r6, asr #1 a70: e18334a5 orr r3, r3, r5, lsr #9 a74: e5cc3000 strb r3, [ip] *pc = (StartAddr >> 17) & 0xff; a78: e1a038a5 mov r3, r5, lsr #17 a7c: e5cc3000 strb r3, [ip] if(~addr_cyc_2) a80: e59f3050 ldr r3, [pc, #80] ; ad8 <.text+0xad8> a84: e5d33000 ldrb r3, [r3] a88: e3730001 cmn r3, #1 ; 0x1 *pc = (StartAddr >> 25) & 0xff; a8c: 11a03ca5 movne r3, r5, lsr #25 a90: 15cc3000 strneb r3, [ip] NANDWait (); a94: ebffff5e bl 814 <NANDWait> pc = (volatile unsigned char *)NAND_IO; a98: e3a0c5d2 mov ip, #880803840 ; 0x34800000 for(j = 0; j < 256; j++) { a9c: e3a02000 mov r2, #0 ; 0x0 *((unsigned char *)pBuf) = *pc; aa0: e5dc3000 ldrb r3, [ip] aa4: e4c43001 strb r3, [r4], #1 aa8: e2822001 add r2, r2, #1 ; 0x1 aac: e35200ff cmp r2, #255 ; 0xff ab0: dafffffa ble aa0 <NANDRead_1K+0x218> ab4: e2866001 add r6, r6, #1 ; 0x1 ab8: e3560003 cmp r6, #3 ; 0x3 abc: daffffe5 ble a58 <NANDRead_1K+0x1d0> pBuf++; } } } } #endif return 1024; } ac0: e3a00b01 mov r0, #1024 ; 0x400 ac4: e8bd81f0 ldmia sp!, {r4, r5, r6, r7, r8, pc} ac8: 00000e88 andeq r0, r0, r8, lsl #29 acc: 00000ea8 andeq r0, r0, r8, lsr #29 ad0: 00000ea9 andeq r0, r0, r9, lsr #29 ad4: 34800002 strcc r0, [r0], #2 ad8: 00000eaa andeq r0, r0, sl, lsr #29 adc: 000001ff streqd r0, [r0], -pc ae0: 000003ff streqd r0, [r0], -pc 00000ae4 <NANDClose>: int NANDClose(void) { return 1; } ae4: e3a00001 mov r0, #1 ; 0x1 ae8: e1a0f00e mov pc, lr 00000aec <SPIOpen>: unsigned char addr_len = 1; int SPIOpen(void) { aec: e52de004 str lr, [sp, #-4]! #ifdef SPI_FUNC_ENA SPI_REG_WRITE_HALF(SPI_SSIENR,0x0); #if 0 if(SPI_REG_READ_BYTES(SMC_BOOT) & 0x2) SPI_REG_WRITE_HALF(SPI_BAUDR, 0x37); /* 0x4 0xc8(256K)*/ else SPI_REG_WRITE_HALF(SPI_BAUDR, 0x37); /* SPI_BDINIT */ #endif SPI_REG_WRITE_HALF(SPI_BAUDR, 0xc8); SPI_REG_WRITE_HALF(SPI_SER , 0x1); SPI_REG_WRITE_HALF(SPI_CTRLR0, SPI_CR0INI|(((SPI_REG_READ_BYTES(SMC_BOOT)) & 0xc)<<4)); addr_len=SPI_REG_READ_BYTES(SMC_BOOT) >> 5; #else asm_reset_spi(); af0: eb000007 bl b14 <asm_reset_spi> #endif return 1; } af4: e3a00001 mov r0, #1 ; 0x1 af8: e49df004 ldr pc, [sp], #4 00000afc <SPIRead_1K>: int SPIRead_1K(unsigned int StartAddr, unsigned char *Buf) { afc: e52de004 str lr, [sp, #-4]! #ifdef SPI_FUNC_ENA int i = 0; int j = 0; assert((StartAddr & 0x3ff) == 0); SPI_REG_WRITE_HALF(SPI_SSIENR,0x0); SPI_REG_WRITE_HALF(SPI_CTRLR1, SPI_CR1INI); SPI_REG_WRITE_HALF(SPI_SSIENR,0x1); SPI_REG_WRITE_HALF(SPI_DR,0x3); if(addr_len>=2) SPI_REG_WRITE_HALF(SPI_DR,((StartAddr>>16) & 0xff)); if(addr_len>=1) SPI_REG_WRITE_HALF(SPI_DR,((StartAddr>>8) & 0xff)); SPI_REG_WRITE_HALF(SPI_DR,(StartAddr & 0xff)); while(i<=SPI_CR1INI) { while(!(j=SPI_REG_READ_BYTES(SPI_RX_CNT))); while(j>0) { Buf[i]=SPI_REG_READ_BYTES(SPI_DR); ++i; --j; } } SPI_REG_WRITE_HALF(SPI_SSIENR,0x0); #else asm_spi_read_1k(StartAddr, Buf); b00: eb00000f bl b44 <asm_spi_read_1k> #endif return 1024; } b04: e3a00b01 mov r0, #1024 ; 0x400 b08: e49df004 ldr pc, [sp], #4 00000b0c <SPIClose>: int SPIClose(void) { #ifdef SPI_FUNC_ENA SPI_REG_WRITE_HALF(SPI_SSIENR,0x0); SPI_REG_WRITE_HALF(SPI_SER , 0x0); #endif return 1; } b0c: e3a00001 mov r0, #1 ; 0x1 b10: e1a0f00e mov pc, lr 00000b14 <asm_reset_spi>: LOADREGS(eqea, fp, {r0, r4 - r9, fp, sp, pc}) .globl asm_reset_spi asm_reset_spi: ENTER b14: e1a0c00d mov ip, sp b18: e92ddbf1 stmdb sp!, {r0, r4, r5, r6, r7, r8, r9, fp, ip, lr, pc} b1c: e24cb004 sub fp, ip, #4 ; 0x4 ldr r9, SPI_SSIENR b20: e59f9120 ldr r9, [pc, #288] ; c48 <SPI_SSIENR> mov r0, #0x0 b24: e3a00000 mov r0, #0 ; 0x0 str r0, [r9] b28: e5890000 str r0, [r9] ldr r9, SPI_SSIENR b2c: e59f9114 ldr r9, [pc, #276] ; c48 <SPI_SSIENR> mov r0, #0x1 b30: e3a00001 mov r0, #1 ; 0x1 str r0, [r9] b34: e5890000 str r0, [r9] bl _delay b38: eb00003b bl c2c <_delay> EXIT b3c: e91babf1 ldmdb fp, {r0, r4, r5, r6, r7, r8, r9, fp, sp, pc} mov pc, lr b40: e1a0f00e mov pc, lr 00000b44 <asm_spi_read_1k>: .globl asm_spi_read_1k asm_spi_read_1k: ENTER b44: e1a0c00d mov ip, sp b48: e92ddbf1 stmdb sp!, {r0, r4, r5, r6, r7, r8, r9, fp, ip, lr, pc} b4c: e24cb004 sub fp, ip, #4 ; 0x4 mov r2, r0 b50: e1a02000 mov r2, r0 00000b54 <_reset_spi>: _reset_spi: # configurate spi baud rate ldr r9, SPI_SSIENR b54: e59f90ec ldr r9, [pc, #236] ; c48 <SPI_SSIENR> mov r0, #0x0 b58: e3a00000 mov r0, #0 ; 0x0 str r0, [r9] b5c: e5890000 str r0, [r9] #configurate spi contrl register 0 ldr r9, SPI_CTRLR0 b60: e59f90d8 ldr r9, [pc, #216] ; c40 <SPI_CTRLR0> ldr r0, SPI_CR0INI b64: e59f00f4 ldr r0, [pc, #244] ; c60 <SPI_CR0INI> str r0, [r9] b68: e5890000 str r0, [r9] #configurate spi control register 1 ldr r9, SPI_CTRLR1 b6c: e59f90d0 ldr r9, [pc, #208] ; c44 <SPI_CTRLR1> ldr r0, SPI_CR1INI @4K byte data b70: e59f00ec ldr r0, [pc, #236] ; c64 <SPI_CR1INI> str r0, [r9] b74: e5890000 str r0, [r9] ldr r9, SPI_BAUDR b78: e59f90d0 ldr r9, [pc, #208] ; c50 <SPI_BAUDR> ldr r0, SPI_BDINIT b7c: e59f00d8 ldr r0, [pc, #216] ; c5c <SPI_BDINIT> str r0, [r9] b80: e5890000 str r0, [r9] # select one spi slave ldr r9, SPI_SER b84: e59f90c0 ldr r9, [pc, #192] ; c4c <SPI_SER> mov r0, #0x1 b88: e3a00001 mov r0, #1 ; 0x1 str r0, [r9] b8c: e5890000 str r0, [r9] #enable spi ldr r9, SPI_SSIENR b90: e59f90b0 ldr r9, [pc, #176] ; c48 <SPI_SSIENR> mov r0, #0x1 b94: e3a00001 mov r0, #1 ; 0x1 str r0, [r9] b98: e5890000 str r0, [r9] #bl _delay # configurate contol byte and address ldr r8, SPI_DR b9c: e59f80b4 ldr r8, [pc, #180] ; c58 <SPI_DR> mov r0, #0x3 ba0: e3a00003 mov r0, #3 ; 0x3 str r0, [r8] ba4: e5880000 str r0, [r8] # set addr mov r0, r2 ba8: e1a00002 mov r0, r2 mov r0, r0, lsl #8 bac: e1a00400 mov r0, r0, lsl #8 mov r0, r0, lsr #24 bb0: e1a00c20 mov r0, r0, lsr #24 str r0, [r8] bb4: e5880000 str r0, [r8] mov r0, r2 bb8: e1a00002 mov r0, r2 mov r0, r0, lsl #16 bbc: e1a00800 mov r0, r0, lsl #16 mov r0, r0, lsr #24 bc0: e1a00c20 mov r0, r0, lsr #24 str r0, [r8] bc4: e5880000 str r0, [r8] mov r0, r2 bc8: e1a00002 mov r0, r2 mov r0, r0, lsl #24 bcc: e1a00c00 mov r0, r0, lsl #24 mov r0, r0, lsr #24 bd0: e1a00c20 mov r0, r0, lsr #24 str r0, [r8] bd4: e5880000 str r0, [r8] # set read number ldr r6, SPI_CP_NUM bd8: e59f6090 ldr r6, [pc, #144] ; c70 <SPI_CP_NUM> ldr r7, SPI_SR bdc: e59f7070 ldr r7, [pc, #112] ; c54 <SPI_SR> 00000be0 <_wait_spi>: _wait_spi: teq r6, #0x0 be0: e3360000 teq r6, #0 ; 0x0 beq _end_spi be4: 0a000007 beq c08 <_end_spi> 1: ldr r0, [r7] be8: e5970000 ldr r0, [r7] ands r0, r0, #0x8 bec: e2100008 ands r0, r0, #8 ; 0x8 bne _copy_spi bf0: 1a000000 bne bf8 <_copy_spi> b 1b bf4: eafffffb b be8 <_wait_spi+0x8> 00000bf8 <_copy_spi>: _copy_spi: sub r6, r6, #0x1 bf8: e2466001 sub r6, r6, #1 ; 0x1 ldrb r5, [r8] bfc: e5d85000 ldrb r5, [r8] strb r5, [r1], #0x1 c00: e4c15001 strb r5, [r1], #1 b _wait_spi c04: eafffff5 b be0 <_wait_spi> 00000c08 <_end_spi>: _end_spi: ldr r9, SPI_SER c08: e59f903c ldr r9, [pc, #60] ; c4c <SPI_SER> mov r0, #0x0 c0c: e3a00000 mov r0, #0 ; 0x0 str r0, [r9] c10: e5890000 str r0, [r9] #disable spi ldr r9, SPI_SSIENR c14: e59f902c ldr r9, [pc, #44] ; c48 <SPI_SSIENR> mov r0, #0x0 c18: e3a00000 mov r0, #0 ; 0x0 str r0, [r9] c1c: e5890000 str r0, [r9] b _copy_end c20: eaffffff b c24 <_copy_end> 00000c24 <_copy_end>: _copy_end: EXIT c24: e91babf1 ldmdb fp, {r0, r4, r5, r6, r7, r8, r9, fp, sp, pc} mov pc, lr c28: e1a0f00e mov pc, lr 00000c2c <_delay>: /* delay */ _delay: ldr r6, =15000 c2c: e59f6040 ldr r6, [pc, #64] ; c74 <SPI_CP_NUM+0x4> 1: sub r6, r6, #0x1 c30: e2466001 sub r6, r6, #1 ; 0x1 teq r6, #0x0 c34: e3360000 teq r6, #0 ; 0x0 bne 1b c38: 1afffffc bne c30 <_delay+0x4> mov pc, lr c3c: e1a0f00e mov pc, lr 00000c40 <SPI_CTRLR0>: c40: 10173000 andnes r3, r7, r0 00000c44 <SPI_CTRLR1>: c44: 10173004 andnes r3, r7, r4 00000c48 <SPI_SSIENR>: c48: 10173008 andnes r3, r7, r8 00000c4c <SPI_SER>: c4c: 10173010 andnes r3, r7, r0, lsl r0 00000c50 <SPI_BAUDR>: c50: 10173014 andnes r3, r7, r4, lsl r0 00000c54 <SPI_SR>: c54: 10173028 andnes r3, r7, r8, lsr #32 00000c58 <SPI_DR>: c58: 10173060 andnes r3, r7, r0, rrx 00000c5c <SPI_BDINIT>: c5c: 00000038 andeq r0, r0, r8, lsr r0 00000c60 <SPI_CR0INI>: c60: 000003c7 andeq r0, r0, r7, asr #7 00000c64 <SPI_CR1INI>: c64: 000003ff streqd r0, [r0], -pc 00000c68 <SPI_RX_CNT>: c68: 10173024 andnes r3, r7, r4, lsr #32 00000c6c <SMC_BOOT>: c6c: 10100034 andnes r0, r0, r4, lsr r0 00000c70 <SPI_CP_NUM>: c70: 00000400 andeq r0, r0, r0, lsl #8 c74: 00003a98 muleq r0, r8, sl 00000c78 <x_memset>: void *x_memset( void* dest, int c, int count ) { c78: e52de004 str lr, [sp, #-4]! int i = 0; c7c: e3a03000 mov r3, #0 ; 0x0 if (dest == NULL || count <=0) c80: e1a0e000 mov lr, r0 c84: e1a0c002 mov ip, r2 c88: e1500003 cmp r0, r3 c8c: 11520003 cmpne r2, r3 { return NULL; c90: d1a00003 movle r0, r3 c94: d49df004 ldrle pc, [sp], #4 } while (i < count) { *((char *)dest + i) = (char)c; i++; c98: e1530002 cmp r3, r2 c9c: aa000003 bge cb0 <x_memset+0x38> ca0: e7ce1003 strb r1, [lr, r3] ca4: e2833001 add r3, r3, #1 ; 0x1 ca8: e153000c cmp r3, ip cac: bafffffb blt ca0 <x_memset+0x28> } return dest; cb0: e1a0000e mov r0, lr } cb4: e49df004 ldr pc, [sp], #4 00000cb8 <x_memcpy>: void *x_memcpy( void *dest, const void *src, int count ) { cb8: e1a0c000 mov ip, r0 int i = 0; cbc: e3a00000 mov r0, #0 ; 0x0 if (count <=0) cc0: e3520000 cmp r2, #0 ; 0x0 cc4: d1a0f00e movle pc, lr { return NULL; } for (i = 0; i < count ; i++) cc8: e3a00000 mov r0, #0 ; 0x0 ccc: e1500002 cmp r0, r2 cd0: aa000004 bge ce8 <x_memcpy+0x30> { *((char *)dest + i) = *((char *)src + i); cd4: e7d13000 ldrb r3, [r1, r0] cd8: e7cc3000 strb r3, [ip, r0] cdc: e2800001 add r0, r0, #1 ; 0x1 ce0: e1500002 cmp r0, r2 ce4: bafffffa blt cd4 <x_memcpy+0x1c> } return dest; ce8: e1a0000c mov r0, ip } cec: e1a0f00e mov pc, lr 00000cf0 <x_memcmp>: int x_memcmp(const void* str1, const void* str2, int n) { cf0: e92d4010 stmdb sp!, {r4, lr} register unsigned char *s1 = (unsigned char*)str1; register unsigned char *s2 = (unsigned char*)str2; if (s1 == NULL || s2 == NULL) cf4: e1a0e000 mov lr, r0 cf8: e1a04001 mov r4, r1 cfc: e3510000 cmp r1, #0 ; 0x0 d00: 13500000 cmpne r0, #0 ; 0x0 return 0; d04: 03a00000 moveq r0, #0 ; 0x0 d08: 08bd8010 ldmeqia sp!, {r4, pc} while (n-- > 0) { if (*s1++ != *s2++) return s1[-1] < s2[-1] ? -1 : 1; d0c: e242c001 sub ip, r2, #1 ; 0x1 d10: e3520000 cmp r2, #0 ; 0x0 d14: da00000d ble d50 <x_memcmp+0x60> d18: e4de2001 ldrb r2, [lr], #1 d1c: e4d43001 ldrb r3, [r4], #1 d20: e1520003 cmp r2, r3 d24: 0a000005 beq d40 <x_memcmp+0x50> d28: e55e2001 ldrb r2, [lr, #-1] d2c: e5543001 ldrb r3, [r4, #-1] d30: e1520003 cmp r2, r3 d34: 23a00001 movcs r0, #1 ; 0x1 d38: 33e00000 mvncc r0, #0 ; 0x0 d3c: e8bd8010 ldmia sp!, {r4, pc} d40: e1a0300c mov r3, ip d44: e24cc001 sub ip, ip, #1 ; 0x1 d48: e3530000 cmp r3, #0 ; 0x0 d4c: cafffff1 bgt d18 <x_memcmp+0x28> } return 0; d50: e3a00000 mov r0, #0 ; 0x0 } d54: e8bd8010 ldmia sp!, {r4, pc} 00000d58 <__udivsi3>: unsigned int __udivsi3(unsigned int num, unsigned int den) { unsigned int quot = 0, qbit = 1; d58: e3a02000 mov r2, #0 ; 0x0 d5c: e3a03001 mov r3, #1 ; 0x1 if ( den == 0 ) { d60: e3510000 cmp r1, #0 ; 0x0 ///__divide_error(); return 0; /* If trap returns... */ d64: 01a00002 moveq r0, r2 d68: 01a0f00e moveq pc, lr } /* Left-justify denominator and count shift */ while ( (int)den >= 0 ) { den <<= 1; qbit <<= 1; d6c: e3510000 cmp r1, #0 ; 0x0 d70: ba000002 blt d80 <__udivsi3+0x28> d74: e1a03083 mov r3, r3, lsl #1 d78: e1b01081 movs r1, r1, lsl #1 d7c: 5afffffc bpl d74 <__udivsi3+0x1c> } while ( qbit ) { if ( den <= num ) { num -= den; quot += qbit; } den >>= 1; qbit >>= 1; d80: e3530000 cmp r3, #0 ; 0x0 d84: 0a000005 beq da0 <__udivsi3+0x48> d88: e1510000 cmp r1, r0 d8c: 90610000 rsbls r0, r1, r0 d90: 90822003 addls r2, r2, r3 d94: e1a010a1 mov r1, r1, lsr #1 d98: e1b030a3 movs r3, r3, lsr #1 d9c: 1afffff9 bne d88 <__udivsi3+0x30> } /* if ( rem_p ) *rem_p = num; */ return quot; da0: e1a00002 mov r0, r2 } da4: e1a0f00e mov pc, lr 00000da8 <x_assert>: int x_assert(int exp, char *exp_str, char *file, int line) { volatile char *p; if (!exp) da8: e3500000 cmp r0, #0 ; 0x0 dac: 11a0f00e movne pc, lr db0: e59f2008 ldr r2, [pc, #8] ; dc0 <.text+0xdc0> db4: e3e03000 mvn r3, #0 ; 0x0 { #ifdef ENA_PRINT printf("Assert: FILE%s Line %d:\n", file, line); printf(" : %s:\n", exp_str); getchar(); #else while(1) //Never Stop { /* Stop Simulation */ p = (volatile char *)0x34800001; *p = 0xff; db8: e5c23000 strb r3, [r2] exp = line * line; dbc: eafffffd b db8 <x_assert+0x10> dc0: 34800001 strcc r0, [r0], #1 dc4: 12345678 eornes r5, r4, #125829120 ; 0x7800000 dc8: 9abcdef0 bls fef38990 <SYSTEM_STACK_SIZE+0xfef36990> dcc: aaaaaaaa bge feaab87c <SYSTEM_STACK_SIZE+0xfeaa987c> dd0: 55555555 ldrplb r5, [r5, #-1365] dd4: 00000000 andeq r0, r0, r0 dd8: ffffffff swinv 0x00ffffff ddc: 00000030 andeq r0, r0, r0, lsr r0 de0: 71657246 cmnvc r5, r6, asr #4 de4: 566c7443 strplbt r7, [ip], -r3, asr #8 de8: 65756c61 ldrvsb r6, [r5, #-3169]! dec: 203d3d20 eorcss r3, sp, r0, lsr #26 df0: 64616552 strvsbt r6, [r1], #-1362 df4: 756c6156 strvcb r6, [ip, #-342]! df8: 00000065 andeq r0, r0, r5, rrx dfc: 65522828 ldrvsb r2, [r2, #-2088] e00: 6c615667 stcvsl 6, cr5, [r1], #-412 e04: 26206575 undefined e08: 31783020 cmncc r8, r0, lsr #32 e0c: 3d3d2029 ldccc 0, cr2, [sp, #-164]! e10: 00293120 eoreq r3, r9, r0, lsr #2 e14: 65522828 ldrvsb r2, [r2, #-2088] e18: 6c615667 stcvsl 6, cr5, [r1], #-412 e1c: 26206575 undefined e20: 31783020 cmncc r8, r0, lsr #32 e24: 3d3d2029 ldccc 0, cr2, [sp, #-164]! e28: 00293020 eoreq r3, r9, r0, lsr #32 e2c: 3d207472 cfstrscc mvf7, [r0, #-456]! e30: 0030203d eoreqs r2, r0, sp, lsr r0 e34: 20746572 rsbcss r6, r4, r2, ror r5 e38: 31203d3d teqcc r0, sp, lsr sp e3c: 00343230 eoreqs r3, r4, r0, lsr r2 e40: 61745328 cmnvs r4, r8, lsr #6 e44: 64417472 strvsb r7, [r1], #-1138 e48: 26207264 strcst r7, [r0], -r4, ror #4 e4c: 307e2820 rsbccs r2, lr, r0, lsr #16 e50: 66663378 undefined e54: 3d202929 stccc 9, cr2, [r0, #-164]! e58: 2828203d stmcsda r8!, {r0, r2, r3, r4, r5, sp} e5c: 72617453 rsbvc r7, r1, #1392508928 ; 0x53000000 e60: 64644174 strvsbt r4, [r4], #-372 e64: 202b2072 eorcs r2, fp, r2, ror r0 e68: 657a6953 ldrvsb r6, [sl, #-2387]! e6c: 31202d20 teqcc r0, r0, lsr #26 e70: 20262029 eorcs r2, r6, r9, lsr #32 e74: 3378307e cmncc r8, #126 ; 0x7e e78: 00296666 eoreq r6, r9, r6, ror #12 e7c: 3d3d2069 ldccc 0, cr2, [sp, #-420]! e80: 7a695320 bvc 1a55b08 <SYSTEM_STACK_SIZE+0x1a53b08> e84: 00000065 andeq r0, r0, r5, rrx e88: 61745328 cmnvs r4, r8, lsr #6 e8c: 64417472 strvsb r7, [r1], #-1138 e90: 26207264 strcst r7, [r0], -r4, ror #4 e94: 33783020 cmncc r8, #32 ; 0x20 e98: 20296666 eorcs r6, r9, r6, ror #12 e9c: 30203d3d eorcc r3, r0, sp, lsr sp ea0: 00000000 andeq r0, r0, r0
stulluk/chipbox-uboot
sldr/build/arm_gcc/secu_loader.asm.c
C
gpl-2.0
57,690
package dmesg // #include <sys/syslog.h> import "C" // Facility models well-known log facilities (see man klogctl) type Facility uint const ( LOG_KERN = C.LOG_KERN // kernel messages LOG_USER = C.LOG_USER // random user-level messages LOG_MAIL = C.LOG_MAIL // mail system LOG_DAEMON = C.LOG_DAEMON // system daemons LOG_AUTH = C.LOG_AUTH // security/authorization messages LOG_SYSLOG = C.LOG_SYSLOG // messages generated internally by syslogd LOG_LPR = C.LOG_LPR // line printer subsystem LOG_NEWS = C.LOG_NEWS // network news subsystem LOG_UUCP = C.LOG_UUCP // UUCP subsystem LOG_CRON = C.LOG_CRON // clock daemon LOG_AUTHPRIV = C.LOG_AUTHPRIV // security/authorization messages (private) LOG_FTP = C.LOG_FTP // ftp daemon ) // MaskFacility extracts the facility (bottom 3 bits) from the integer value v. func MaskFacility(v uint) Facility { return Facility((v & 0x03fb) >> 3) }
vosst/csi
dmesg/facility.go
GO
gpl-2.0
981
<?php /* +---------------------------------------------------------------------------+ | Revive Adserver | | http://www.revive-adserver.com | | | | Copyright: See the COPYRIGHT.txt file. | | License: GPLv2 or later, see the LICENSE.txt file. | +---------------------------------------------------------------------------+ */ // Other // Measures // Common Invocation Parameters // Iframe // PopUp // XML-RPC // Support for 3rd party server clicktracking // Support for cachebusting code // IMG invocation selected for tracker with appended code $GLOBALS['strWarning'] = "Cảnh báo"; // Local Invocation
sgreiner/revive-adserver
lib/max/language/vi/invocation.lang.php
PHP
gpl-2.0
865
/** * This class is generated by jOOQ */ package schema.process_engine.tables; /** * This class is generated by jOOQ. */ @javax.annotation.Generated( value = { "http://www.jooq.org", "jOOQ version:3.5.4" }, comments = "This class is generated by jOOQ" ) @java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class ActHiTaskinst extends org.jooq.impl.TableImpl<schema.process_engine.tables.records.ActHiTaskinstRecord> { private static final long serialVersionUID = -477092330; /** * The reference instance of <code>process-engine.ACT_HI_TASKINST</code> */ public static final schema.process_engine.tables.ActHiTaskinst ACT_HI_TASKINST = new schema.process_engine.tables.ActHiTaskinst(); /** * The class holding records for this type */ @Override public java.lang.Class<schema.process_engine.tables.records.ActHiTaskinstRecord> getRecordType() { return schema.process_engine.tables.records.ActHiTaskinstRecord.class; } /** * The column <code>process-engine.ACT_HI_TASKINST.ID_</code>. */ public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.String> ID_ = createField("ID_", org.jooq.impl.SQLDataType.VARCHAR.length(64).nullable(false), this, ""); /** * The column <code>process-engine.ACT_HI_TASKINST.PROC_DEF_ID_</code>. */ public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.String> PROC_DEF_ID_ = createField("PROC_DEF_ID_", org.jooq.impl.SQLDataType.VARCHAR.length(64), this, ""); /** * The column <code>process-engine.ACT_HI_TASKINST.TASK_DEF_KEY_</code>. */ public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.String> TASK_DEF_KEY_ = createField("TASK_DEF_KEY_", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, ""); /** * The column <code>process-engine.ACT_HI_TASKINST.PROC_INST_ID_</code>. */ public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.String> PROC_INST_ID_ = createField("PROC_INST_ID_", org.jooq.impl.SQLDataType.VARCHAR.length(64), this, ""); /** * The column <code>process-engine.ACT_HI_TASKINST.EXECUTION_ID_</code>. */ public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.String> EXECUTION_ID_ = createField("EXECUTION_ID_", org.jooq.impl.SQLDataType.VARCHAR.length(64), this, ""); /** * The column <code>process-engine.ACT_HI_TASKINST.ACT_INST_ID_</code>. */ public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.String> ACT_INST_ID_ = createField("ACT_INST_ID_", org.jooq.impl.SQLDataType.VARCHAR.length(64), this, ""); /** * The column <code>process-engine.ACT_HI_TASKINST.NAME_</code>. */ public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.String> NAME_ = createField("NAME_", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, ""); /** * The column <code>process-engine.ACT_HI_TASKINST.PARENT_TASK_ID_</code>. */ public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.String> PARENT_TASK_ID_ = createField("PARENT_TASK_ID_", org.jooq.impl.SQLDataType.VARCHAR.length(64), this, ""); /** * The column <code>process-engine.ACT_HI_TASKINST.DESCRIPTION_</code>. */ public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.String> DESCRIPTION_ = createField("DESCRIPTION_", org.jooq.impl.SQLDataType.VARCHAR.length(4000), this, ""); /** * The column <code>process-engine.ACT_HI_TASKINST.OWNER_</code>. */ public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.String> OWNER_ = createField("OWNER_", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, ""); /** * The column <code>process-engine.ACT_HI_TASKINST.ASSIGNEE_</code>. */ public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.String> ASSIGNEE_ = createField("ASSIGNEE_", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, ""); /** * The column <code>process-engine.ACT_HI_TASKINST.START_TIME_</code>. */ public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.sql.Timestamp> START_TIME_ = createField("START_TIME_", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, ""); /** * The column <code>process-engine.ACT_HI_TASKINST.END_TIME_</code>. */ public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.sql.Timestamp> END_TIME_ = createField("END_TIME_", org.jooq.impl.SQLDataType.TIMESTAMP, this, ""); /** * The column <code>process-engine.ACT_HI_TASKINST.DURATION_</code>. */ public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.Long> DURATION_ = createField("DURATION_", org.jooq.impl.SQLDataType.BIGINT, this, ""); /** * The column <code>process-engine.ACT_HI_TASKINST.DELETE_REASON_</code>. */ public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.String> DELETE_REASON_ = createField("DELETE_REASON_", org.jooq.impl.SQLDataType.VARCHAR.length(4000), this, ""); /** * The column <code>process-engine.ACT_HI_TASKINST.PRIORITY_</code>. */ public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.lang.Integer> PRIORITY_ = createField("PRIORITY_", org.jooq.impl.SQLDataType.INTEGER, this, ""); /** * The column <code>process-engine.ACT_HI_TASKINST.DUE_DATE_</code>. */ public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.sql.Timestamp> DUE_DATE_ = createField("DUE_DATE_", org.jooq.impl.SQLDataType.TIMESTAMP, this, ""); /** * The column <code>process-engine.ACT_HI_TASKINST.FOLLOW_UP_DATE_</code>. */ public final org.jooq.TableField<schema.process_engine.tables.records.ActHiTaskinstRecord, java.sql.Timestamp> FOLLOW_UP_DATE_ = createField("FOLLOW_UP_DATE_", org.jooq.impl.SQLDataType.TIMESTAMP, this, ""); /** * Create a <code>process-engine.ACT_HI_TASKINST</code> table reference */ public ActHiTaskinst() { this("ACT_HI_TASKINST", null); } /** * Create an aliased <code>process-engine.ACT_HI_TASKINST</code> table reference */ public ActHiTaskinst(java.lang.String alias) { this(alias, schema.process_engine.tables.ActHiTaskinst.ACT_HI_TASKINST); } private ActHiTaskinst(java.lang.String alias, org.jooq.Table<schema.process_engine.tables.records.ActHiTaskinstRecord> aliased) { this(alias, aliased, null); } private ActHiTaskinst(java.lang.String alias, org.jooq.Table<schema.process_engine.tables.records.ActHiTaskinstRecord> aliased, org.jooq.Field<?>[] parameters) { super(alias, schema.process_engine.Process_engine.PROCESS_ENGINE, aliased, parameters, ""); } /** * {@inheritDoc} */ @Override public org.jooq.UniqueKey<schema.process_engine.tables.records.ActHiTaskinstRecord> getPrimaryKey() { return schema.process_engine.Keys.KEY_ACT_HI_TASKINST_PRIMARY; } /** * {@inheritDoc} */ @Override public java.util.List<org.jooq.UniqueKey<schema.process_engine.tables.records.ActHiTaskinstRecord>> getKeys() { return java.util.Arrays.<org.jooq.UniqueKey<schema.process_engine.tables.records.ActHiTaskinstRecord>>asList(schema.process_engine.Keys.KEY_ACT_HI_TASKINST_PRIMARY); } /** * {@inheritDoc} */ @Override public schema.process_engine.tables.ActHiTaskinst as(java.lang.String alias) { return new schema.process_engine.tables.ActHiTaskinst(alias, this); } /** * Rename this table */ public schema.process_engine.tables.ActHiTaskinst rename(java.lang.String name) { return new schema.process_engine.tables.ActHiTaskinst(name, null); } }
marcoargenti/Cleaner
src/main/java/schema/process_engine/tables/ActHiTaskinst.java
Java
gpl-2.0
7,875
<?php /************************************************************************************* * tsql.php * -------- * Author: Duncan Lock (dunc@dflock.co.uk) * Copyright: (c) 2006 Duncan Lock (http://dflock.co.uk/), Nigel McNie (http://qbnz.com/highlighter) * Release Version: 1.0.7.15 * CVS Revision Version: $Revision: 1.8.2.6 $ * Date Started: 2005/11/22 * Last Modified: $Date: 2006/09/23 02:05:48 $ * * T-SQL language file for GeSHi. * * CHANGES * ------- * 2004/01/23 (1.0.0) * - First Release * * TODO (updated 2006/01/23) * ------------------------- * ************************************************************************************* * * This file is part of GeSHi. * * GeSHi 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. * * GeSHi 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 GeSHi; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ************************************************************************************/ $language_data = array ( 'LANG_NAME' => 'T-SQL', 'COMMENT_SINGLE' => array(1 => '--'), 'COMMENT_MULTI' => array('/*' => '*/'), 'CASE_KEYWORDS' => GESHI_CAPS_UPPER, 'QUOTEMARKS' => array("'", '"'), 'ESCAPE_CHAR' => '\\', 'KEYWORDS' => array( 1 => array( /* This will be highlighted in blue */ // Datatypes 'bigint', 'int', 'smallint', 'tinyint', 'bit', 'decimal', 'numeric', 'money', 'smallmoney', 'float', 'real', 'datetime', 'smalldatetime', 'char', 'varchar', 'text', 'nchar', 'nvarchar', 'ntext', 'binary', 'varbinary', 'image', 'cursor', 'sql_variant', 'table', 'timestamp', 'uniqueidentifier', // Keywords 'ABSOLUTE', 'ACTION', 'ADD', 'ADMIN', 'AFTER', 'AGGREGATE', 'ALIAS', 'ALLOCATE', 'ALTER', 'ARE', 'ARRAY', 'AS', 'ASC', 'ASSERTION', 'AT', 'AUTHORIZATION', 'BACKUP', 'BEFORE', 'BEGIN', 'BINARY', 'BIT', 'BLOB', 'BOOLEAN', 'BOTH', 'BREADTH', 'BREAK', 'BROWSE', 'BULK', 'BY', 'CALL', 'CASCADE', 'CASCADED', 'CASE', 'CAST', 'CATALOG', 'CHAR', 'CHARACTER', 'CHECK', 'CHECKPOINT', 'CLASS', 'CLOB', 'CLOSE', 'CLUSTERED', 'COALESCE', 'COLLATE', 'COLLATION', 'COLUMN', 'COMMIT', 'COMPLETION', 'COMPUTE', 'CONNECT', 'CONNECTION', 'CONSTRAINT', 'CONSTRAINTS', 'CONSTRUCTOR', 'CONTAINS', 'CONTAINSTABLE', 'CONTINUE', 'CONVERT', 'CORRESPONDING', 'CREATE', 'CUBE', 'CURRENT', 'CURRENT_DATE', 'CURRENT_PATH', 'CURRENT_ROLE', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_USER', 'CURSOR', 'CYCLE', 'DATA', 'DATABASE', 'DATE', 'DAY', 'DBCC', 'DEALLOCATE', 'DEC', 'DECIMAL', 'DECLARE', 'DEFAULT', 'DEFERRABLE', 'DEFERRED', 'DELETE', 'DENY', 'DEPTH', 'DEREF', 'DESC', 'DESCRIBE', 'DESCRIPTOR', 'DESTROY', 'DESTRUCTOR', 'DETERMINISTIC', 'DIAGNOSTICS', 'DICTIONARY', 'DISCONNECT', 'DISK', 'DISTINCT', 'DISTRIBUTED', 'DOMAIN', 'DOUBLE', 'DROP', 'DUMMY', 'DUMP', 'DYNAMIC', 'EACH', 'ELSE', 'END', 'END-EXEC', 'EQUALS', 'ERRLVL', 'ESCAPE', 'EVERY', 'EXCEPT', 'EXCEPTION', 'EXEC', 'EXECUTE', 'EXIT', 'EXTERNAL', 'FALSE', 'FETCH', 'FILE', 'FILLFACTOR', 'FIRST', 'FLOAT', 'FOR', 'FOREIGN', 'FOUND', 'FREE', 'FREETEXT', 'FREETEXTTABLE', 'FROM', 'FULL', 'FUNCTION', 'GENERAL', 'GET', 'GLOBAL', 'GOTO', 'GRANT', 'GROUP', 'GROUPING', 'HAVING', 'HOLDLOCK', 'HOST', 'HOUR', 'IDENTITY', 'IDENTITY_INSERT', 'IDENTITYCOL', 'IF', 'IGNORE', 'IMMEDIATE', 'INDEX', 'INDICATOR', 'INITIALIZE', 'INITIALLY', 'INNER', 'INOUT', 'INPUT', 'INSERT', 'INT', 'INTEGER', 'INTERSECT', 'INTERVAL', 'INTO', 'IS', 'ISOLATION', 'ITERATE', 'KEY', 'KILL', 'LANGUAGE', 'LARGE', 'LAST', 'LATERAL', 'LEADING', 'LEFT', 'LESS', 'LEVEL', 'LIMIT', 'LINENO', 'LOAD', 'LOCAL', 'LOCALTIME', 'LOCALTIMESTAMP', 'LOCATOR', 'MAP', 'MATCH', 'MINUTE', 'MODIFIES', 'MODIFY', 'MODULE', 'MONTH', 'NAMES', 'NATIONAL', 'NATURAL', 'NCHAR', 'NCLOB', 'NEW', 'NEXT', 'NO', 'NOCHECK', 'NONCLUSTERED', 'NONE', 'NULLIF', 'NUMERIC', 'OBJECT', 'OF', 'OFF', 'OFFSETS', 'OLD', 'ON', 'ONLY', 'OPEN', 'OPENDATASOURCE', 'OPENQUERY', 'OPENROWSET', 'OPENXML', 'OPERATION', 'OPTION', 'ORDER', 'ORDINALITY', 'OUT', 'OUTPUT', 'OVER', 'PAD', 'PARAMETER', 'PARAMETERS', 'PARTIAL', 'PATH', 'PERCENT', 'PLAN', 'POSTFIX', 'PRECISION', 'PREFIX', 'PREORDER', 'PREPARE', 'PRESERVE', 'PRIMARY', 'PRINT', 'PRIOR', 'PRIVILEGES', 'PROC', 'PROCEDURE', 'PUBLIC', 'RAISERROR', 'READ', 'READS', 'READTEXT', 'REAL', 'RECONFIGURE', 'RECURSIVE', 'REF', 'REFERENCES', 'REFERENCING', 'RELATIVE', 'REPLICATION', 'RESTORE', 'RESTRICT', 'RESULT', 'RETURN', 'RETURNS', 'REVOKE', 'RIGHT', 'ROLE', 'ROLLBACK', 'ROLLUP', 'ROUTINE', 'ROW', 'ROWGUIDCOL', 'ROWS', 'RULE', 'SAVE', 'SAVEPOINT', 'SCHEMA', 'SCOPE', 'SCROLL', 'SEARCH', 'SECOND', 'SECTION', 'SELECT', 'SEQUENCE', 'SESSION', 'SESSION_USER', 'SET', 'SETS', 'SETUSER', 'SHUTDOWN', 'SIZE', 'SMALLINT', 'SPACE', 'SPECIFIC', 'SPECIFICTYPE', 'SQL', 'SQLEXCEPTION', 'SQLSTATE', 'SQLWARNING', 'START', 'STATE', 'STATEMENT', 'STATIC', 'STATISTICS', 'STRUCTURE', 'SYSTEM_USER', 'TABLE', 'TEMPORARY', 'TERMINATE', 'TEXTSIZE', 'THAN', 'THEN', 'TIME', 'TIMESTAMP', 'TIMEZONE_HOUR', 'TIMEZONE_MINUTE', 'TO', 'TOP', 'TRAILING', 'TRAN', 'TRANSACTION', 'TRANSLATION', 'TREAT', 'TRIGGER', 'TRUE', 'TRUNCATE', 'TSEQUAL', 'UNDER', 'UNION', 'UNIQUE', 'UNKNOWN', 'UNNEST', 'UPDATE', 'UPDATETEXT', 'USAGE', 'USE', 'USER', 'USING', 'VALUE', 'VALUES', 'VARCHAR', 'VARIABLE', 'VARYING', 'VIEW', 'WAITFOR', 'WHEN', 'WHENEVER', 'WHERE', 'WHILE', 'WITH', 'WITHOUT', 'WORK', 'WRITE', 'WRITETEXT', 'YEAR', 'ZONE', 'UNCOMMITTED', 'NOCOUNT', ), 2 => array( /* Built-in functions Highlighted in pink. */ //Configuration Functions '@@DATEFIRST','@@OPTIONS','@@DBTS','@@REMSERVER','@@LANGID','@@SERVERNAME', '@@LANGUAGE','@@SERVICENAME','@@LOCK_TIMEOUT','@@SPID','@@MAX_CONNECTIONS','@@TEXTSIZE', '@@MAX_PRECISION','@@VERSION','@@NESTLEVEL', //Cursor Functions '@@CURSOR_ROWS','@@FETCH_STATUS', //Date and Time Functions 'DATEADD','DATEDIFF','DATENAME','DATEPART','DAY','GETDATE','GETUTCDATE','MONTH','YEAR', //Mathematical Functions 'ABS','DEGREES','RAND','ACOS','EXP','ROUND','ASIN','FLOOR','SIGN', 'ATAN','LOG','SIN','ATN2','LOG10','SQUARE','CEILING','PI','SQRT','COS', 'POWER','TAN','COT','RADIANS', //Meta Data Functions 'COL_LENGTH','fn_listextendedproperty','COL_NAME','FULLTEXTCATALOGPROPERTY', 'COLUMNPROPERTY','FULLTEXTSERVICEPROPERTY','DATABASEPROPERTY','INDEX_COL', 'DATABASEPROPERTYEX','INDEXKEY_PROPERTY','DB_ID','INDEXPROPERTY','DB_NAME', 'OBJECT_ID','FILE_ID','OBJECT_NAME','FILE_NAME','OBJECTPROPERTY','FILEGROUP_ID', '@@PROCID','FILEGROUP_NAME','SQL_VARIANT_PROPERTY','FILEGROUPPROPERTY', 'TYPEPROPERTY','FILEPROPERTY', //Security Functions 'fn_trace_geteventinfo','IS_SRVROLEMEMBER','fn_trace_getfilterinfo','SUSER_SID', 'fn_trace_getinfo','SUSER_SNAME','fn_trace_gettable','USER_ID','HAS_DBACCESS', 'IS_MEMBER', //String Functions 'ASCII','NCHAR','SOUNDEX','CHAR','PATINDEX','SPACE','CHARINDEX', 'REPLACE','STR','DIFFERENCE','QUOTENAME','STUFF','LEFT','REPLICATE', 'SUBSTRING','LEN','REVERSE','UNICODE','LOWER','RIGHT','UPPER','LTRIM', 'RTRIM', //System Functions 'APP_NAME','COLLATIONPROPERTY','@@ERROR','fn_helpcollations', 'fn_servershareddrives','fn_virtualfilestats','FORMATMESSAGE', 'GETANSINULL','HOST_ID','HOST_NAME','IDENT_CURRENT','IDENT_INCR', 'IDENT_SEED','@@IDENTITY','ISDATE','ISNUMERIC','PARSENAME','PERMISSIONS', '@@ROWCOUNT','ROWCOUNT_BIG','SCOPE_IDENTITY','SERVERPROPERTY','SESSIONPROPERTY', 'STATS_DATE','@@TRANCOUNT','USER_NAME', //System Statistical Functions '@@CONNECTIONS','@@PACK_RECEIVED','@@CPU_BUSY','@@PACK_SENT', 'fn_virtualfilestats','@@TIMETICKS','@@IDLE','@@TOTAL_ERRORS','@@IO_BUSY', '@@TOTAL_READ','@@PACKET_ERRORS','@@TOTAL_WRITE', //Text and Image Functions 'TEXTPTR','TEXTVALID', //Aggregate functions 'AVG', 'MAX', 'BINARY_CHECKSUM', 'MIN', 'CHECKSUM', 'SUM', 'CHECKSUM_AGG', 'STDEV', 'COUNT', 'STDEVP', 'COUNT_BIG', 'VAR', 'GROUPING', 'VARP' ), 3 => array( /* System stored procedures Higlighted dark brown */ //Active Directory Procedures 'sp_ActiveDirectory_Obj', 'sp_ActiveDirectory_SCP', //Catalog Procedures 'sp_column_privileges', 'sp_special_columns', 'sp_columns', 'sp_sproc_columns', 'sp_databases', 'sp_statistics', 'sp_fkeys', 'sp_stored_procedures', 'sp_pkeys', 'sp_table_privileges', 'sp_server_info', 'sp_tables', //Cursor Procedures 'sp_cursor_list', 'sp_describe_cursor_columns', 'sp_describe_cursor', 'sp_describe_cursor_tables', //Database Maintenance Plan Procedures 'sp_add_maintenance_plan', 'sp_delete_maintenance_plan_db', 'sp_add_maintenance_plan_db', 'sp_delete_maintenance_plan_job', 'sp_add_maintenance_plan_job', 'sp_help_maintenance_plan', 'sp_delete_maintenance_plan', //Distributed Queries Procedures 'sp_addlinkedserver', 'sp_indexes', 'sp_addlinkedsrvlogin', 'sp_linkedservers', 'sp_catalogs', 'sp_primarykeys', 'sp_column_privileges_ex', 'sp_serveroption', 'sp_columns_ex', 'sp_table_privileges_ex', 'sp_droplinkedsrvlogin', 'sp_tables_ex', 'sp_foreignkeys', //Full-Text Search Procedures 'sp_fulltext_catalog', 'sp_help_fulltext_catalogs_cursor', 'sp_fulltext_column', 'sp_help_fulltext_columns', 'sp_fulltext_database', 'sp_help_fulltext_columns_cursor', 'sp_fulltext_service', 'sp_help_fulltext_tables', 'sp_fulltext_table', 'sp_help_fulltext_tables_cursor', 'sp_help_fulltext_catalogs', //Log Shipping Procedures 'sp_add_log_shipping_database', 'sp_delete_log_shipping_database', 'sp_add_log_shipping_plan', 'sp_delete_log_shipping_plan', 'sp_add_log_shipping_plan_database', 'sp_delete_log_shipping_plan_database', 'sp_add_log_shipping_primary', 'sp_delete_log_shipping_primary', 'sp_add_log_shipping_secondary', 'sp_delete_log_shipping_secondary', 'sp_can_tlog_be_applied', 'sp_get_log_shipping_monitor_info', 'sp_change_monitor_role', 'sp_remove_log_shipping_monitor', 'sp_change_primary_role', 'sp_resolve_logins', 'sp_change_secondary_role', 'sp_update_log_shipping_monitor_info', 'sp_create_log_shipping_monitor_account', 'sp_update_log_shipping_plan', 'sp_define_log_shipping_monitor', 'sp_update_log_shipping_plan_database', //OLE Automation Extended Stored Procedures 'sp_OACreate', 'sp_OAMethod', 'sp_OADestroy', 'sp_OASetProperty', 'sp_OAGetErrorInfo', 'sp_OAStop', 'sp_OAGetProperty', //Replication Procedures 'sp_add_agent_parameter', 'sp_enableagentoffload', 'sp_add_agent_profile', 'sp_enumcustomresolvers', 'sp_addarticle', 'sp_enumdsn', 'sp_adddistpublisher', 'sp_enumfullsubscribers', 'sp_adddistributiondb', 'sp_expired_subscription_cleanup', 'sp_adddistributor', 'sp_generatefilters', 'sp_addmergealternatepublisher', 'sp_getagentoffloadinfo', 'sp_addmergearticle', 'sp_getmergedeletetype', 'sp_addmergefilter', 'sp_get_distributor', 'sp_addmergepublication', 'sp_getqueuedrows', 'sp_addmergepullsubscription', 'sp_getsubscriptiondtspackagename', 'sp_addmergepullsubscription_agent', 'sp_grant_publication_access', 'sp_addmergesubscription', 'sp_help_agent_default', 'sp_addpublication', 'sp_help_agent_parameter', 'sp_addpublication_snapshot', 'sp_help_agent_profile', 'sp_addpublisher70', 'sp_helparticle', 'sp_addpullsubscription', 'sp_helparticlecolumns', 'sp_addpullsubscription_agent', 'sp_helparticledts', 'sp_addscriptexec', 'sp_helpdistpublisher', 'sp_addsubscriber', 'sp_helpdistributiondb', 'sp_addsubscriber_schedule', 'sp_helpdistributor', 'sp_addsubscription', 'sp_helpmergealternatepublisher', 'sp_addsynctriggers', 'sp_helpmergearticle', 'sp_addtabletocontents', 'sp_helpmergearticlecolumn', 'sp_adjustpublisheridentityrange', 'sp_helpmergearticleconflicts', 'sp_article_validation', 'sp_helpmergeconflictrows', 'sp_articlecolumn', 'sp_helpmergedeleteconflictrows', 'sp_articlefilter', 'sp_helpmergefilter', 'sp_articlesynctranprocs', 'sp_helpmergepublication', 'sp_articleview', 'sp_helpmergepullsubscription', 'sp_attachsubscription', 'sp_helpmergesubscription', 'sp_browsesnapshotfolder', 'sp_helppublication', 'sp_browsemergesnapshotfolder', 'sp_help_publication_access', 'sp_browsereplcmds', 'sp_helppullsubscription', 'sp_change_agent_parameter', 'sp_helpreplfailovermode', 'sp_change_agent_profile', 'sp_helpreplicationdboption', 'sp_changearticle', 'sp_helpreplicationoption', 'sp_changedistpublisher', 'sp_helpsubscriberinfo', 'sp_changedistributiondb', 'sp_helpsubscription', 'sp_changedistributor_password', 'sp_ivindexhasnullcols', 'sp_changedistributor_property', 'sp_helpsubscription_properties', 'sp_changemergearticle', 'sp_link_publication', 'sp_changemergefilter', 'sp_marksubscriptionvalidation', 'sp_changemergepublication', 'sp_mergearticlecolumn', 'sp_changemergepullsubscription', 'sp_mergecleanupmetadata', 'sp_changemergesubscription', 'sp_mergedummyupdate', 'sp_changepublication', 'sp_mergesubscription_cleanup', 'sp_changesubscriber', 'sp_publication_validation', 'sp_changesubscriber_schedule', 'sp_refreshsubscriptions', 'sp_changesubscriptiondtsinfo', 'sp_reinitmergepullsubscription', 'sp_changesubstatus', 'sp_reinitmergesubscription', 'sp_change_subscription_properties', 'sp_reinitpullsubscription', 'sp_check_for_sync_trigger', 'sp_reinitsubscription', 'sp_copymergesnapshot', 'sp_removedbreplication', 'sp_copysnapshot', 'sp_repladdcolumn', 'sp_copysubscription', 'sp_replcmds', 'sp_deletemergeconflictrow', 'sp_replcounters', 'sp_disableagentoffload', 'sp_repldone', 'sp_drop_agent_parameter', 'sp_repldropcolumn', 'sp_drop_agent_profile', 'sp_replflush', 'sp_droparticle', 'sp_replicationdboption', 'sp_dropanonymouseagent', 'sp_replication_agent_checkup', 'sp_dropdistpublisher', 'sp_replqueuemonitor', 'sp_dropdistributiondb', 'sp_replsetoriginator', 'sp_dropmergealternatepublisher', 'sp_replshowcmds', 'sp_dropdistributor', 'sp_repltrans', 'sp_dropmergearticle', 'sp_restoredbreplication', 'sp_dropmergefilter', 'sp_revoke_publication_access', 'sp_scriptsubconflicttable', 'sp_dropmergepublication', 'sp_script_synctran_commands', 'sp_dropmergepullsubscription', 'sp_setreplfailovermode', 'sp_showrowreplicainfo', 'sp_dropmergesubscription', 'sp_subscription_cleanup', 'sp_droppublication', 'sp_table_validation', 'sp_droppullsubscription', 'sp_update_agent_profile', 'sp_dropsubscriber', 'sp_validatemergepublication', 'sp_dropsubscription', 'sp_validatemergesubscription', 'sp_dsninfo', 'sp_vupgrade_replication', 'sp_dumpparamcmd', //Security Procedures 'sp_addalias', 'sp_droprolemember', 'sp_addapprole', 'sp_dropserver', 'sp_addgroup', 'sp_dropsrvrolemember', 'sp_addlinkedsrvlogin', 'sp_dropuser', 'sp_addlogin', 'sp_grantdbaccess', 'sp_addremotelogin', 'sp_grantlogin', 'sp_addrole', 'sp_helpdbfixedrole', 'sp_addrolemember', 'sp_helpgroup', 'sp_addserver', 'sp_helplinkedsrvlogin', 'sp_addsrvrolemember', 'sp_helplogins', 'sp_adduser', 'sp_helpntgroup', 'sp_approlepassword', 'sp_helpremotelogin', 'sp_changedbowner', 'sp_helprole', 'sp_changegroup', 'sp_helprolemember', 'sp_changeobjectowner', 'sp_helprotect', 'sp_change_users_login', 'sp_helpsrvrole', 'sp_dbfixedrolepermission', 'sp_helpsrvrolemember', 'sp_defaultdb', 'sp_helpuser', 'sp_defaultlanguage', 'sp_MShasdbaccess', 'sp_denylogin', 'sp_password', 'sp_dropalias', 'sp_remoteoption', 'sp_dropapprole', 'sp_revokedbaccess', 'sp_dropgroup', 'sp_revokelogin', 'sp_droplinkedsrvlogin', 'sp_setapprole', 'sp_droplogin', 'sp_srvrolepermission', 'sp_dropremotelogin', 'sp_validatelogins', 'sp_droprole', //SQL Mail Procedures 'sp_processmail', 'xp_sendmail', 'xp_deletemail', 'xp_startmail', 'xp_findnextmsg', 'xp_stopmail', 'xp_readmail', //SQL Profiler Procedures 'sp_trace_create', 'sp_trace_setfilter', 'sp_trace_generateevent', 'sp_trace_setstatus', 'sp_trace_setevent', //SQL Server Agent Procedures 'sp_add_alert', 'sp_help_jobhistory', 'sp_add_category', 'sp_help_jobschedule', 'sp_add_job', 'sp_help_jobserver', 'sp_add_jobschedule', 'sp_help_jobstep', 'sp_add_jobserver', 'sp_help_notification', 'sp_add_jobstep', 'sp_help_operator', 'sp_add_notification', 'sp_help_targetserver', 'sp_add_operator', 'sp_help_targetservergroup', 'sp_add_targetservergroup', 'sp_helptask', 'sp_add_targetsvrgrp_member', 'sp_manage_jobs_by_login', 'sp_addtask', 'sp_msx_defect', 'sp_apply_job_to_targets', 'sp_msx_enlist', 'sp_delete_alert', 'sp_post_msx_operation', 'sp_delete_category', 'sp_purgehistory', 'sp_delete_job', 'sp_purge_jobhistory', 'sp_delete_jobschedule', 'sp_reassigntask', 'sp_delete_jobserver', 'sp_remove_job_from_targets', 'sp_delete_jobstep', 'sp_resync_targetserver', 'sp_delete_notification', 'sp_start_job', 'sp_delete_operator', 'sp_stop_job', 'sp_delete_targetserver', 'sp_update_alert', 'sp_delete_targetservergroup', 'sp_update_category', 'sp_delete_targetsvrgrp_member', 'sp_update_job', 'sp_droptask', 'sp_update_jobschedule', 'sp_help_alert', 'sp_update_jobstep', 'sp_help_category', 'sp_update_notification', 'sp_help_downloadlist', 'sp_update_operator', 'sp_helphistory', 'sp_update_targetservergroup', 'sp_help_job', 'sp_updatetask', 'xp_sqlagent_proxy_account', //System Procedures 'sp_add_data_file_recover_suspect_db', 'sp_helpconstraint', 'sp_addextendedproc', 'sp_helpdb', 'sp_addextendedproperty', 'sp_helpdevice', 'sp_add_log_file_recover_suspect_db', 'sp_helpextendedproc', 'sp_addmessage', 'sp_helpfile', 'sp_addtype', 'sp_helpfilegroup', 'sp_addumpdevice', 'sp_helpindex', 'sp_altermessage', 'sp_helplanguage', 'sp_autostats', 'sp_helpserver', 'sp_attach_db', 'sp_helpsort', 'sp_attach_single_file_db', 'sp_helpstats', 'sp_bindefault', 'sp_helptext', 'sp_bindrule', 'sp_helptrigger', 'sp_bindsession', 'sp_indexoption', 'sp_certify_removable', 'sp_invalidate_textptr', 'sp_configure', 'sp_lock', 'sp_create_removable', 'sp_monitor', 'sp_createstats', 'sp_procoption', 'sp_cycle_errorlog', 'sp_recompile', 'sp_datatype_info', 'sp_refreshview', 'sp_dbcmptlevel', 'sp_releaseapplock', 'sp_dboption', 'sp_rename', 'sp_dbremove', 'sp_renamedb', 'sp_delete_backuphistory', 'sp_resetstatus', 'sp_depends', 'sp_serveroption', 'sp_detach_db', 'sp_setnetname', 'sp_dropdevice', 'sp_settriggerorder', 'sp_dropextendedproc', 'sp_spaceused', 'sp_dropextendedproperty', 'sp_tableoption', 'sp_dropmessage', 'sp_unbindefault', 'sp_droptype', 'sp_unbindrule', 'sp_executesql', 'sp_updateextendedproperty', 'sp_getapplock', 'sp_updatestats', 'sp_getbindtoken', 'sp_validname', 'sp_help', 'sp_who', //Web Assistant Procedures 'sp_dropwebtask', 'sp_makewebtask', 'sp_enumcodepages', 'sp_runwebtask', //XML Procedures 'sp_xml_preparedocument', 'sp_xml_removedocument', //General Extended Procedures 'xp_cmdshellxp_logininfo', 'xp_enumgroups', 'xp_msver', 'xp_findnextmsgxp_revokelogin', 'xp_grantlogin', 'xp_sprintf', 'xp_logevent', 'xp_sqlmaint', 'xp_loginconfig', 'xp_sscanf', //API System Stored Procedures 'sp_cursor', 'sp_cursorclose', 'sp_cursorexecute', 'sp_cursorfetch', 'sp_cursoropen', 'sp_cursoroption', 'sp_cursorprepare', 'sp_cursorunprepare', 'sp_execute', 'sp_prepare', 'sp_unprepare', //Misc 'sp_createorphan', 'sp_droporphans', 'sp_reset_connection', 'sp_sdidebug' ), 4 => array( //Function/sp's higlighted brown. 'fn_helpcollations', 'fn_listextendedproperty ', 'fn_servershareddrives', 'fn_trace_geteventinfo', 'fn_trace_getfilterinfo', 'fn_trace_getinfo', 'fn_trace_gettable', 'fn_virtualfilestats', ), ), 'SYMBOLS' => array( '!', '!=', '%', '&', '&&', '(', ')', '*', '+', '-', '/', '<', '<<', '<=', '<=>', '<>', '=', '>', '>=', '>>', '^', 'ALL', 'AND', 'ANY', 'BETWEEN', 'CROSS', 'EXISTS', 'IN', 'JOIN', 'LIKE', 'NOT', 'NULL', 'OR', 'OUTER', 'SOME', '|', '||', '~' ), 'CASE_SENSITIVE' => array( GESHI_COMMENTS => true, 1 => false, 2 => false, 3 => false, 4 => false, ), 'STYLES' => array( 'KEYWORDS' => array( 1 => 'color: #0000FF;', 2 => 'color: #FF00FF;', 3 => 'color: #AF0000;', 4 => 'color: #AF0000;' ), 'COMMENTS' => array( 1 => 'color: #008080;', 'MULTI' => 'color: #008080;' ), 'ESCAPE_CHAR' => array( 0 => 'color: #000099; font-weight: bold;' ), 'BRACKETS' => array( 0 => 'color: #808080;' ), 'STRINGS' => array( 0 => 'color: #FF0000;' ), 'NUMBERS' => array( 0 => 'color: #000;' ), 'METHODS' => array( 1 => 'color: #202020;', 2 => 'color: #202020;' ), 'SYMBOLS' => array( 0 => 'color: #808080;' ), 'REGEXPS' => array( ), 'SCRIPT' => array( ) ), 'URLS' => array( 1 => '', 2 => '', 3 => '', 4 => '' ), 'OOLANG' => true, 'OBJECT_SPLITTERS' => array( 1 => '.' ), 'REGEXPS' => array( ), 'STRICT_MODE_APPLIES' => GESHI_NEVER, 'SCRIPT_DELIMITERS' => array( ), 'HIGHLIGHT_STRICT_BLOCK' => array( ) ); ?>
SOSWEB-CH/atelier-rl
inc/geshi/tsql.php
PHP
gpl-2.0
21,616
/* * (c) Copyright 1992, 1993 by Panagiotis Tsirigotis * All rights reserved. The file named COPYRIGHT specifies the terms * and conditions for redistribution. */ #include "config.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <unistd.h> #include <syslog.h> #ifdef _APPLE_ #undef HAVE_MMAP #endif #include "impl.h" #include "sio.h" int __sio_n_descriptors = 0 ; __sio_descriptor_t *__sio_descriptors = NULL ; static sio_status_e setup_read_buffer( __sio_id_t *idp, unsigned buf_size ); #ifndef MAP_FAILED #define MAP_FAILED ((void *)-1) #endif /* * Code for finalization */ #ifdef HAVE_FINALIZATION_FUNCTION static int finalizer_installed ; SIO_DEFINE_FIN( sio_cleanup ) { (void) Sflush( SIO_FLUSH_ALL ) ; } #endif /* HAVE_FINALIZATION_FUNCTION */ #ifdef HAVE_MMAP #define CHAR_NULL ((char *)0) /* * PAGES_MAPPED gives the size of each map unit in pages */ #define PAGES_MAPPED 2 static size_t map_unit_size = 0 ; /* bytes */ static size_t page_size = 0 ; /* bytes */ static mapd_s *mmap_descriptors = NULL ; #define MDP( fd ) ( mmap_descriptors + (fd) ) /* * NOTES ON MEMORY MAPPING: * * 1. Memory mapping works only for file descriptors opened for input * 2. Mapping an object to a part of the address space where another * object is mapped will cause the old mapping to disappear (i.e. mmap * will not fail) * * Memory mapping interface: * SIO_MMAP : maps a file into a portion of the address space. * SIO_MUNMAP: unmap a portion of the address space * SIO_MNEED: indicate to the OS that we will need a portion of * our address space. * * The map_unit_size variable defines how much of the file is mapped at * a time. It is a multiple of the operating system page size. It is * not less than SIO_BUFFER_SIZE unless SIO_BUFFER_SIZE is not a * multiple of the page size (so the SIO_BUFFER_SIZE overrides * PAGES_MAPPED). * * NOTE: All memory mapping code is in this file only */ /* * Macros used by the memory mapping code */ #define FIRST_TIME( dp ) ( dp->buf == NULL ) /* * Functions to support memory mapping: * * try_memory_mapping * buffer_setup * __sio_switch * initial_map * map_unit */ /* * try_memory_mapping attempts to setup the specified descriptor * for memory mapping. * It returns FAILURE if it fails and SUCCESS if it is successful. * If HAVE_MMAP is not defined, the function is defined to be FAILURE. * * Sets fields: * memory_mapped: TRUE or FALSE * * Also sets the following fields if memory_mapped is TRUE: * file_offset, file_size, buffer_size * */ static sio_status_e try_memory_mapping( int fd, __sio_id_t *idp, const struct stat *stp ) { int access_f ; /* * Do not try memory mapping if: * 1) The file is not a regular file * 2) The file is a regular file but has zero-length * 3) The file pointer is not positioned at the beginning of the file * 4) The fcntl to obtain the file descriptor flags fails * 5) The access mode is not O_RDONLY or O_RDWR * * The operations are done in this order to avoid the system calls * if possible. */ if ( ( ( stp->st_mode & S_IFMT ) != S_IFREG ) || ( stp->st_size == 0 ) || ( lseek( fd, (long)0, 1 ) != 0 ) || ( ( access_f = fcntl( fd, F_GETFL, 0 ) ) == -1 ) || ( ( access_f &= 0x3 ) != O_RDONLY && access_f != O_RDWR ) ) { idp->memory_mapped = FALSE ; return( FAILURE ) ; } /* * Determine page_size and map_unit_size. * Note that the code works even if PAGES_MAPPED is 0. */ if ( page_size == 0 ) { page_size = getpagesize() ; map_unit_size = page_size * PAGES_MAPPED ; if ( map_unit_size < SIO_BUFFER_SIZE ) { if ( map_unit_size != 0 && SIO_BUFFER_SIZE % map_unit_size == 0 ) map_unit_size = SIO_BUFFER_SIZE ; else map_unit_size = page_size ; } } MDP(fd)->file_offset = 0 ; MDP(fd)->file_size = stp->st_size ; idp->buffer_size = map_unit_size ; idp->buf = CHAR_NULL ; idp->memory_mapped = TRUE ; return( SUCCESS ) ; } /* * Copy the current_unit to the primary buffer * * Sets fields: start, end, nextb * Also sets the file pointer */ static void buffer_setup( __sio_id_t *idp, int fd, const struct map_unit *mu_cur, const struct map_unit *mu_next ) { off_t new_offset ; sio_memcopy( mu_cur->addr, idp->buf, mu_cur->valid_bytes ) ; idp->start = idp->buf ; idp->end = idp->buf + mu_cur->valid_bytes ; idp->nextb = idp->buf + ( idp->nextb - mu_cur->addr ) ; if ( mu_next->addr != CHAR_NULL ) new_offset = MDP(fd)->file_offset - mu_next->valid_bytes ; else new_offset = MDP(fd)->file_offset ; (void) lseek( fd, new_offset, 0 ) ; } /* * Switch from memory mapping to buffered I/O * If any mapping has occurred, then the current unit is * copied into the buffer that is allocated. * Any data in the next unit is ignored. * We rely on idp->buf to identify the current unit (so it * better be equal to the address of one of the units). * * Sets fields: * start, end, nextb */ sio_status_e __sio_switch( __sio_id_t *idp, int fd ) { mapd_s *mdp = MDP( fd ) ; struct map_unit *mu_cur, *mu_next ; unsigned buffer_size = idp->buffer_size ; char *buf_addr = idp->buf ; int first_time = FIRST_TIME( idp ) ; /* * Initialize stream for buffering */ if ( setup_read_buffer( idp, buffer_size ) == FAILURE ) return( FAILURE ) ; if ( ! first_time ) { /* * Find current, next unit */ if ( buf_addr == mdp->first_unit.addr ) { mu_cur = &mdp->first_unit ; mu_next = &mdp->second_unit ; } else { mu_cur = &mdp->second_unit ; mu_next = &mdp->first_unit ; } buffer_setup( idp, fd, mu_cur, mu_next ) ; /* * Destroy all mappings */ (void) SIO_MUNMAP( mu_cur->addr, mu_cur->mapped_bytes ) ; if ( mu_next->addr != NULL ) (void) SIO_MUNMAP( mu_next->addr, mu_next->mapped_bytes ) ; } else idp->start = idp->end = idp->nextb = idp->buf ; idp->memory_mapped = FALSE ; return( SUCCESS ) ; } /* * initial_map does the first memory map on the file descriptor. * It attempts to map both units. * The mapping always starts at file offset 0. * * SETS FIELDS: * first_unit.*, second_unit.* * file_offset * * Returns: * number of bytes mapped in first_unit * or * 0 to indicate that mmap failed. */ static int initial_map( mapd_s *mdp, int fd ) { caddr_t addr ; size_t requested_length = 2 * map_unit_size ; size_t mapped_length = MIN( (size_t)mdp->file_size, requested_length ) ; size_t bytes_left ; size_t bytes_in_unit ; addr = SIO_MMAP( CHAR_NULL, mapped_length, fd, 0 ) ; if ( addr == MAP_FAILED ) return( 0 ) ; SIO_MNEED( addr, mapped_length ) ; /* * Map as much as possible in the first unit */ bytes_in_unit = MIN( mapped_length, map_unit_size ) ; mdp->first_unit.addr = addr ; mdp->first_unit.mapped_bytes = bytes_in_unit ; mdp->first_unit.valid_bytes = bytes_in_unit ; /* * If there is more, map it in the second unit. */ bytes_left = mapped_length - bytes_in_unit ; if ( bytes_left != 0 ) { mdp->second_unit.addr = addr + bytes_in_unit ; mdp->second_unit.mapped_bytes = bytes_left ; mdp->second_unit.valid_bytes = bytes_left ; } else mdp->second_unit.addr = CHAR_NULL ; mdp->file_offset = mapped_length ; return( mdp->first_unit.valid_bytes ) ; } /* * ALGORITHM: * * if ( there are more bytes in the file ) * { * map them at the given unit * update offset * issue SIO_MNEED() * } * else * unmap the unit */ static sio_status_e map_unit( mapd_s *mdp, int fd, struct map_unit *mup ) { size_t bytes_left = mdp->file_size - mdp->file_offset ; size_t bytes_to_map = MIN( bytes_left, map_unit_size ) ; if ( bytes_to_map != 0 ) { if ( SIO_MMAP( mup->addr, bytes_to_map, fd, mdp->file_offset ) == MAP_FAILED ) return( FAILURE ) ; /* XXX: need to do more ? */ mup->valid_bytes = bytes_to_map ; ASSERT( mup->valid_bytes <= mup->mapped_bytes ) ; mdp->file_offset += bytes_to_map ; SIO_MNEED( mup->addr, mup->valid_bytes ) ; } else { (void) SIO_MUNMAP( mup->addr, mup->mapped_bytes ) ; mup->addr = CHAR_NULL ; } return( SUCCESS ) ; } #else #define try_memory_mapping( x, y, z ) FAILURE #endif /* HAVE_MMAP */ static sio_status_e setup_read_buffer( __sio_id_t *idp, unsigned buf_size ) { char *buf ; /* * First allocate space for 2 buffers: primary and auxiliary */ buf = malloc( buf_size * 2 ) ; if ( buf == NULL ) return( FAILURE ) ; /* * The descriptor buf field should point to the start of the main buffer */ idp->buf = buf + buf_size ; idp->buffer_size = buf_size ; return( SUCCESS ) ; } static sio_status_e init_input_stream( __sio_id_t *idp, int fd, const struct stat *stp ) { /* * First initialize the fields relevant to buffering: buf, buffer_size */ if ( try_memory_mapping( fd, idp, stp ) == FAILURE ) { /* * Try to use normal buffering */ unsigned buf_size = (unsigned) ( stp->st_blksize ? stp->st_blksize : SIO_BUFFER_SIZE ) ; if ( setup_read_buffer( idp, buf_size ) == FAILURE ) return( FAILURE ) ; } /* * Initialize remaining descriptor fields */ idp->max_line_length = 2 * idp->buffer_size - 1 ; idp->start = idp->end = idp->nextb = idp->buf ; idp->tied_fd = SIO_NO_TIED_FD ; return( SUCCESS ) ; } static sio_status_e init_output_stream( __sio_od_t *odp, int fd, const struct stat *stp ) { unsigned buf_size ; char *buf ; buf_size = (unsigned) ( stp->st_blksize ? stp->st_blksize : SIO_BUFFER_SIZE ) ; buf = malloc( buf_size ) ; if ( buf == NULL ) return( FAILURE ) ; /* * Initialize buffering fields */ odp->buf = buf ; odp->buffer_size = buf_size ; odp->buf_end = odp->buf + buf_size ; /* * Initialize remaining fields */ odp->start = odp->nextb = odp->buf ; if ( isatty( fd ) ) odp->buftype = SIO_LINEBUF ; if ( fd == 2 ) odp->buftype = SIO_NOBUF ; return( SUCCESS ) ; } #ifndef HAVE_ISATTY #ifdef HAVE_SYSVTTY #include <termio.h> static int isatty( int fd ) { struct termio t ; if ( ioctl( fd, TCGETA, &t ) == -1 && errno == ENOTTY ) return( FALSE ) ; else return( TRUE ) ; } #endif /* HAVE_SYSVTTY */ #ifdef HAVE_BSDTTY #include <sgtty.h> static int isatty( int fd ) { struct sgttyb s ; if ( ioctl( fd, TIOCGETP, &s ) == -1 && errno == ENOTTY ) return( FALSE ) ; else return( TRUE ) ; } #endif /* HAVE_BSDTTY */ #endif /* ! HAVE_ISATTY */ /* * Initialize stream I/O for a file descriptor. * * Arguments: * fd: file descriptor * dp: descriptor pointer * stream_type: either __SIO_INPUT_STREAM or __SIO_OUTPUT_STREAM * * Returns * 0 if successful * SIO_ERR if the file descriptor is not valid (sets errno) * exits if stream_type is not __SIO_INPUT_STREAM or __SIO_OUTPUT_STREAM */ int __sio_init( __sio_descriptor_t *dp, int fd, enum __sio_stream stream_type ) { struct stat st ; memset(dp, 0, sizeof(__sio_descriptor_t)); if ( fd >= __sio_n_descriptors ) { errno = EBADF ; return( SIO_ERR ) ; } if ( fstat( fd, &st ) == -1 ) return( SIO_ERR ) ; switch ( stream_type ) { case __SIO_INPUT_STREAM: if ( init_input_stream( IDP( dp ), fd, &st ) == FAILURE ) return( SIO_ERR ) ; break ; case __SIO_OUTPUT_STREAM: if ( init_output_stream( ODP( dp ), fd, &st ) == FAILURE ) return( SIO_ERR ) ; break ; default: terminate( "SIO __sio_init: bad stream type (internal error).\n" ) ; /* NOTREACHED */ } dp->stream_type = stream_type ; dp->initialized = TRUE ; #ifdef HAVE_FINALIZATION_FUNCTION if ( ! finalizer_installed ) { if ( ! SIO_FINALIZE( sio_cleanup ) ) { char *s = "SIO __sio_init: finalizer installation failed\n" ; (void) write( 2, s, strlen( s ) ) ; } else finalizer_installed = TRUE ; } #endif /* HAVE_FINALIZATION_FUNCTION */ return( 0 ) ; } /* * __sio_writef writes the data in the buffer to the file descriptor. * * It tries to write as much data as possible until either all data * are written or an error occurs. EINTR is the only error that is * ignored. * In case an error occurs but some data were written, that number * is returned instead of SIO_ERR. * * Fields modified: * When successful: start, nextb * When not successful: start * * Return value: * Number of bytes written * SIO_ERR, if write(2) fails and no data were written */ int __sio_writef( __sio_od_t *odp, int fd ) { int b_in_buffer ; int cc_total = 0 ; /* * Make sure we don't exceed the buffer limits * Maybe we should log this ? XXX */ if ( odp->nextb > odp->buf_end ) odp->nextb = odp->buf_end ; b_in_buffer = odp->nextb - odp->start ; if ( b_in_buffer == 0 ) return( 0 ) ; for ( ;; ) { int cc ; cc = write( fd, odp->start, b_in_buffer ) ; if ( cc == b_in_buffer ) { odp->start = odp->nextb = odp->buf ; cc_total += cc ; break ; } else if ( cc == -1 ) { if ( errno == EINTR ) continue ; else /* * If some bytes were written, return that number, otherwise * return SIO_ERR */ return( ( cc_total != 0 ) ? cc_total : SIO_ERR ) ; } else /* some bytes were written */ { odp->start += cc ; /* advance start of buffer */ b_in_buffer -= cc ; /* decrease number bytes left in buffer */ cc_total += cc ; /* count the bytes that were written */ } } return( cc_total ) ; } /* * __sio_readf reads data from the file descriptor into the buffer. * Unlike __sio_writef it does NOT try to read as much data as will fit * in the buffer. It ignores EINTR. * * Returns: # of bytes read or SIO_ERR * * Fields set: * If it does not return SIO_ERR, it sets start, nextb, end * If it returns SIO_ERR, it does not change anything */ static int __sio_readf( __sio_id_t *idp, int fd ) { int cc ; /* * First check for a tied fd and flush the stream if necessary * * XXX the return value of __sio_writef is not checked. * Is that right ? */ if ( idp->tied_fd != SIO_NO_TIED_FD ) (void) __sio_writef( &__SIO_OD( idp->tied_fd ), idp->tied_fd ) ; #ifdef HAVE_MMAP if ( idp->memory_mapped ) { mapd_s *mdp = MDP( fd ) ; /* * The functions initial_map and map_unit may fail. * In either case, we switch to buffered I/O. * If initial_map fails, we have read no data, so we * should perform a read(2). * If map_unit fails (for the next unit), we still have * the data in the current unit, so we can return. */ if ( FIRST_TIME( idp ) ) { cc = initial_map( mdp, fd ) ; if ( cc > 0 ) idp->buf = mdp->first_unit.addr ; else { if ( __sio_switch( idp, fd ) == FAILURE ) return( SIO_ERR ) ; cc = -1 ; } } else { struct map_unit *mu_cur, *mu_next ; if ( idp->buf == mdp->first_unit.addr ) { mu_cur = &mdp->first_unit ; mu_next = &mdp->second_unit ; } else { mu_cur = &mdp->second_unit ; mu_next = &mdp->first_unit ; } if ( mu_next->addr != NULL ) { idp->buf = mu_next->addr ; cc = mu_next->valid_bytes ; /* * XXX: Here we may return SIO_ERR even though there * are data in the current unit because the switch * fails (possibly because malloc failed). */ if ( map_unit( mdp, fd, mu_cur ) == FAILURE && __sio_switch( idp, fd ) == FAILURE ) return( SIO_ERR ) ; } else cc = 0 ; } if ( cc >= 0 ) { idp->end = idp->buf + cc ; idp->start = idp->nextb = idp->buf ; return( cc ) ; } } #endif /* HAVE_MMAP */ for ( ;; ) { cc = read( fd, idp->buf, (int) idp->buffer_size ) ; if ( cc == -1 ) if ( errno == EINTR ) continue ; else return( SIO_ERR ) ; else break ; } idp->end = idp->buf + cc ; idp->start = idp->nextb = idp->buf ; return( cc ) ; } /* * __sio_extend_buffer is used by Srdline to extend the buffer * If successful, it returns the number of bytes that have been read. * If it fails (because of end-of-file or I/O error), it returns 0 or -1. * * Fields modified: * idp->start points to the start of the buffer area (which is in the * auxiliary buffer) * Also, if successful, idp->nextb is set to idp->buf, idp->end is modified. */ int __sio_extend_buffer( __sio_id_t *idp, int fd, int b_left ) { int b_read ; /* * copy to auxiliary buffer */ if ( b_left ) sio_memcopy( idp->nextb, idp->buf - b_left, b_left ) ; b_read = __sio_readf( idp, fd ) ; idp->start = idp->buf - b_left ; return( b_read ) ; } /* * __sio_more tries to read more data from the given file descriptor iff * there is free space in the buffer. * __sio_more is used only by Srdline and only AFTER __sio_extend_buffer * has been called. This implies that * a) this is not a memory mapped file * b) __sio_readf has been called (so we don't need to check for tied fd's * * Fields modified (only if successful): * idp->end * * Return value: the number of bytes read. */ int __sio_more( __sio_id_t *idp, int fd ) { int b_left = &idp->buf[ idp->buffer_size ] - idp->end ; int cc ; if ( b_left <= 0 ) return( 0 ) ; for ( ;; ) { cc = read( fd, idp->end, b_left ) ; if ( cc >= 0 ) { idp->end += cc ; return( cc ) ; } else if ( errno == EINTR ) continue ; else return( SIO_ERR ) ; } } /* * Finalize a buffer by unmapping the file or freeing the malloc'ed memory. * This function is only called by Sclose. We always free memory even if * SIO_ERR is returned as long as the descriptor was initialized. */ int Sdone( int fd ) { __sio_descriptor_t *dp ; int ret_val = 0; if ( fd < 0 || fd >= __sio_n_descriptors ) { errno = EBADF ; return( SIO_ERR ) ; } dp = &__sio_descriptors[ fd ] ; if ( ! DESCRIPTOR_INITIALIZED( dp ) ) { errno = EBADF ; return( SIO_ERR ) ; } switch ( dp->stream_type ) { case __SIO_INPUT_STREAM: { __sio_id_t *idp = IDP( dp ) ; #ifdef HAVE_MMAP if ( idp->memory_mapped ) { mapd_s *mdp = MDP( fd ) ; if ( mdp->first_unit.addr != CHAR_NULL ) (void) SIO_MUNMAP( mdp->first_unit.addr, mdp->first_unit.mapped_bytes ) ; if ( mdp->second_unit.addr != CHAR_NULL ) (void) SIO_MUNMAP( mdp->second_unit.addr, mdp->second_unit.mapped_bytes ) ; idp->memory_mapped = FALSE ; } else #endif /* HAVE_MMAP */ free( idp->buf - idp->buffer_size ) ; idp->nextb = idp->end = NULL ; } break ; case __SIO_OUTPUT_STREAM: { __sio_od_t *odp = ODP( dp ) ; if ( Sflush( fd ) == SIO_ERR ) ret_val = SIO_ERR; free( odp->buf ) ; odp->nextb = odp->buf_end = NULL ; } break ; default: terminate( "SIO Sdone: bad stream type\n" ) ; } memset( dp, 0, sizeof(__sio_descriptor_t) ); dp->initialized = FALSE ; return ret_val; } static char *sioexpand( char *area, unsigned old_size, unsigned new_size, int is_static ) { char *new_area ; if ( is_static ) { if ( ( new_area = malloc( new_size ) ) == NULL ) return( NULL ) ; sio_memcopy( area, new_area, old_size ) ; } else if ( ( new_area = realloc( area, new_size ) ) == NULL ) return( NULL ) ; return( new_area ) ; } /* * Expand the descriptor array (and if we use memory mapping the * memory mapping descriptors). We first expand the memory mapping * descriptors. * There is no problem if the expansion of the SIO descriptors fails * (i.e. there is no need to undo anything). */ int Smorefds(int fd) { char *p ; int is_static ; unsigned new_size, old_size ; int n_fds = 4; /* Let's bump 4 at a time for hysteresis */ /* If the fd is out of range of the proposed size, make n_fds big enough */ if (fd >= (__sio_n_descriptors+n_fds)) n_fds += fd - __sio_n_descriptors; #ifdef HAVE_MMAP old_size = __sio_n_descriptors * sizeof( mapd_s ) ; new_size = n_fds * sizeof( mapd_s ) ; new_size += old_size; is_static = ( mmap_descriptors == NULL ) ; p = sioexpand( (char *)mmap_descriptors, old_size, new_size, is_static ) ; if ( p == NULL ) return( SIO_ERR ) ; memset(p+old_size, 0, new_size-old_size); mmap_descriptors = (mapd_s *) p ; #endif /* HAVE_MMAP */ old_size = __sio_n_descriptors * sizeof( __sio_descriptor_t ) ; new_size = n_fds * sizeof( __sio_descriptor_t ) ; new_size += old_size; is_static = ( __sio_descriptors == NULL ) ; p = sioexpand( (char *)__sio_descriptors, old_size, new_size, is_static ) ; if ( p == NULL ) return( SIO_ERR ) ; memset(p+old_size, 0, new_size-old_size); __sio_descriptors = (__sio_descriptor_t *) p ; __sio_n_descriptors += n_fds ; return( 0 ) ; } void terminate(const char *msg) { syslog(LOG_CRIT, "%s", msg); (void) abort() ; _exit( 1 ) ; /* NOT REACHED */ }
curtiszimmerman/rcp100
src/system/xinetd-2.3.14/libs/src/sio/siosup.c
C
gpl-2.0
23,037
#include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <netinet/in.h> #include <neteconet/ec.h> #include <stdlib.h> #include "net.h" void econet_gen_sockaddr(struct sockaddr **addr, socklen_t *addrlen) { struct sockaddr_ec *ec; ec = malloc(sizeof(struct sockaddr_ec)); if (ec == NULL) return; ec->sec_family = PF_ECONET; ec->port = rand(); ec->cb = rand(); ec->type = rand(); ec->addr.station = rand(); ec->addr.net = rand(); ec->cookie = rand(); *addr = (struct sockaddr *) ec; *addrlen = sizeof(struct sockaddr_ec); }
jcmvbkbc/trinity-xtensa
net/proto-econet.c
C
gpl-2.0
558
<!doctype html> <html lang=en > <head> <meta charset=utf-8 > <title>FGx Globe Crossfeed Dailies Replay R1</title> <meta name=viewport content='width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no' > <meta name=description content='' > <meta name=keywords content='WebGL,Three.js,JavaScript,GitHub,FOSS,3D,STEM' > <meta name=date content='' > </head> <body> <!-- <script src=https://mrdoob.github.io/three.js/build/three.min.js ></script> <script src=https://mrdoob.github.io/three.js/examples/js/controls/OrbitControls.js ></script> <script src=https://mrdoob.github.io/three.js/examples/js/libs/stats.min.js ></script> --> <script src=https://rawgit.com/mrdoob/three.js/dev/build/three.min.js ></script> <script src=https://rawgit.com/mrdoob/three.js/dev/examples/js/controls/OrbitControls.js ></script> <script src=https://rawgit.com/mrdoob/three.js/dev/examples/js/libs/stats.min.js ></script> <script src=earth-globe-displacement-r2.js ></script> <script> console.time( 'timer 0' ); var fileName = 'https://fgx.github.io/crossfeed-dailies/flights-2016-07-30.csv'; var count = 1; var lines; var radius = 6371; var meshes = []; var callsigns = []; var trails = []; var pi = Math.PI, pi05 = pi * 0.5, pi2 = pi + pi; var d2r = pi / 180, r2d = 180 / pi; // degrees / radians var v = function ( x, y, z ){ return new THREE.Vector3( x, y, z ); }; var center = v( 0, 0, 0 ); var stats, renderer, scene, camera, controls, mesh; var axisHelper, ambientLight, drawSeaLevel; init(); function init() { var css, hamburger, menu; var geometry, material; var gridHelper, axisHelper; var txt = '<p>lorem ipsum, quia dolor sit, amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt, ut labore et dolore magnam aliquam quaerat voluptatem. ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? quis autem vel eum iure reprehenderit, qui in ea voluptate velit esse, quam nihil molestiae consequatur, vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur?</p>'; css = document.head.appendChild( document.createElement( 'style' ) ); css.innerHTML = 'body { font: 12pt monospace; margin: 0; overflow: hidden; }' + 'a { color: crimson; text-decoration: none; }' + 'button, input[type=button] { background-color: #ccc; border: 2px #fff solid; color: #322; }' + 'input[type=range] { -webkit-appearance: none; -moz-appearance: none; background-color: #ddd; width: 160px; }' + 'input[type=range]::-moz-range-thumb { background-color: #888; border-radius: 0; width: 10px; }' + 'input[type=range]::-webkit-slider-thumb { -webkit-appearance: none; background-color: #888; height: 20px; width: 10px; }' + 'summary { outline: none; }' + 'summary h3 { display:inline; }' + '.popUp { background-color: white; left: 150px; border: 1px solid red; opacity: 1.0; padding: 5px; position: absolute; width: 120px; z-index: 10; }' + '#bars { color: crimson; cursor: pointer; font-size: 24pt; text-decoration: none; }' + '#container { left: 0; position: absolute; transition: left 1s; }' + '#hamburger { background-color: #eee; left: 325px; position: absolute; top: 20px; }' + '#menu { background-color: #eee; border: 1px #ccc solid; max-height: ' + window.innerHeight + 'px; overflow: auto; padding: 0 10px; position: absolute; width: 300px; }' + '#menu h2 { margin: 0; }' + ''; container = document.body.appendChild( document.createElement( 'div' ) ); container.id = 'container'; container.innerHTML = '<div id=menu >' + '<h2>' + '<a href=http://jaanga.github.io title="Jaanga - your 3D happy place" > &#x2766 </a><br>' + '<a href="" title="Click here to refresh this page" >' + document.title + '</a>' + ' ~ <a href=index.html#readme.md onmouseover=popHelp.style.display=""; onmouseout=popHelp.style.display="none"; > &#x24D8; </a>' + '</h2>' + '<div class=popUp id=popHelp style=display:none; ><p>Hi there!</p>Click the i-in-circle, info icon for latest updates.</div>' + '<p>A very basic 3D globe with a displacement map material.</p>' + // '<p><input type=checkbox id=onchange=controls.autoRotate=this.checked; checked > Auto-rotation</p>' + '<div id=menuContents ></div>' + '<div id=menuGlobe ></div>' + '<div id=menuInfo ></div>' + '<details>' + '<summary><h3>about</h3></summary>' + '<p>Copyright &copy; 2016 Jaanga authors. <a href=http://jaanga.github.io/home/r4/index.html#http://jaanga.github.io/jaanga-copyright-and-mit-license.md >MIT license</a>.</p>' + '<p>Click the \'i in a circle\' icon for more <a href=index.html#readme.md title="Click here for help and information" >help</a>.</p>' + '<p></p>' + '</details>' + '<hr>' + '<center><a href=javascript:menu.scrollTop=0; style=text-decoration:none; onmouseover=pop2.style.display=""; onmouseout=pop2.style.display="none"; ><h1> &#x2766 <h1></a></center>' + '<div class=popUp id=pop2 style=display:none;bottom:10px; >Jaanga - your 3D happy place.<br>Click here to return to the top of the page</div>' + // '<center title="dingbat" ><h1><a href=javascript:window.scrollTo(0,0); style=text-decoration:none; > &#x2766 </a></h1></center>' + '</div>' + '<div id=hamburger onclick=container.style.left=container.style.left===""?"-325px":""; >' + '<div id=bars title="Click this hamburger to slide the menu" > &#9776 </div>' + '</div>' + ''; if ( window.self !== window.top ) { container.style.left = '-325px'; } stats = new Stats(); stats.domElement.style.cssText = 'position: absolute; right: 0; top: 0;' ; document.body.appendChild( stats.domElement ); stats.domElement.style.display = window.innerWidth < 500 ? 'none' : ''; window.addEventListener( 'resize', onWindowResize, false ); window.addEventListener( 'click', function() { controls.autoRotate = false; }, false ); renderer = new THREE.WebGLRenderer( { alpha: 1, antialias: true } ); // renderer.setClearColor( 0xf0f0f0 ); // renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( window.innerWidth, window.innerHeight ); document.body.appendChild( renderer.domElement ); camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 40000 ); camera.position.set( 12000, 12000, 12000 ); controls = new THREE.OrbitControls( camera, renderer.domElement ); controls.maxDistance = 30000; controls.autoRotate = true; scene = new THREE.Scene(); // helpers axisHelper = new THREE.AxisHelper( 10000 ); scene.add( axisHelper ); // assets ambientLight = new THREE.AmbientLight( 0xffffff ); scene.add( ambientLight ); directionalLight = new THREE.DirectionalLight( 0x888888, 1 ); directionalLight.position.set( 1, 1, 1.6 ); // points to US scene.add( directionalLight ); drawGlobe(); getCrossfeedData( fileName ); } function getCrossfeedData( fName) { // var fileName, text, lines; xhr = new XMLHttpRequest(); xhr.open( 'GET', fName, true ); xhr.onload = callback; xhr.send( null ); function callback() { text = xhr.responseText; // lines = text.split(/\r\n|\n/); lines = text.split( '\n' ).map( function( line ) { return line.split( ',' ); } ); console.log( lines[ 0 ] ); console.log( lines[ 1 ] ); console.log( 'lines', lines.length ); animate(); } } function readLine( i ) { // var line, callsign, index; geometry, material, mesh; var position; line = lines[ i ]; callsign = line[ 1 ]; index = callsigns.indexOf( callsign ); if ( index === -1 ) { callsigns.push( callsign ); geometry = new THREE.BoxGeometry( 100, 100, 100 ); material = new THREE.MeshNormalMaterial(); mesh = new THREE.Mesh( geometry, material ); scene.add( mesh ); index = meshes.length; meshes.push( mesh ); mesh.userData.points = []; mesh.trail = new THREE.Object3D();; } mesh = meshes[ index ]; position = latLonToXYZ( ( radius + 1000 + 0.05 * parseFloat( line[ 4 ] ) ) , parseFloat( line[ 2 ] ) * d2r, parseFloat( line[ 3 ] ) * d2r ); mesh.position.copy( position ); mesh.userData.points.push( position ); scene.remove( mesh.userData.trail ); if ( center.distanceTo( position ) < 10000 ) { geometry = new THREE.Geometry(); geometry.vertices = mesh.userData.points.slice( -500 ); material = new THREE.LineBasicMaterial( { color: 0xff0000 } ); mesh.userData.trail = new THREE.Line( geometry, material ); scene.add( mesh.userData.trail ); } menuInfo.innerHTML = i + ' ' + line[ 1 ]; } function latLonToXYZ( radius, latitude, longitude ) { x = radius * Math.sin( latitude ) * Math.cos( longitude ) y = radius * Math.sin( latitude ) * Math.sin( longitude ) z = radius * Math.cos( latitude ) return new THREE.Vector3( x, y, z ); } function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize( window.innerWidth, window.innerHeight ); stats.domElement.style.display = window.innerWidth < 500 ? 'none' : ''; } function removeAll() { for ( var i = 0; i < callsigns.length; i++ ) { scene.remove( meshes[ i ].userData.trail ); meshes[ i ].userData.points = []; } } function animate() { requestAnimationFrame( animate ); controls.update(); stats.update(); for ( var i = 0; i < 100; i++ ) { if ( count > lines.length - 2 ) { removeAll(); count = 1; } readLine( count++ ); } renderer.render( scene, camera ); } </script> </body> </html>
fgx/fgx.github.io
sandbox/globe-crossfeed-replay/globe-crossfeed-replay-r1.html
HTML
gpl-2.0
9,657
import os import sys import unittest from unittest.mock import patch, MagicMock sys.path.append(os.path.join(os.path.dirname(__file__), '../../src/')) from katello.agent.pulp import libdnf @unittest.skipIf('dnf' not in sys.modules, "Dnf not present") class TestLibDnf(unittest.TestCase): def test_package_update_on_advisories(self): advisories = set(["RHSA-1000"]) packages = set([("foo","1.0"), ("bar","2.0")]) def applicable_advisories(items): self.assertEqual(advisories, items.ids) return [(MagicMock(), packages)] mock_libdnf = MagicMock() mock_libdnf.__enter__ = lambda instance: instance mock_libdnf.applicable_advisories = applicable_advisories with patch('katello.agent.pulp.libdnf.LibDnf', return_value= mock_libdnf): package = libdnf.Package() package.update([],advisories) #strip the evrs out of the package packages = set([pack[0] for pack in packages]) mock_libdnf.upgrade.assert_called_with(packages) def test_package_update_all(self): advisories = set() packages = set() mock_libdnf = MagicMock() mock_libdnf.__enter__ = lambda instance: instance with patch('katello.agent.pulp.libdnf.LibDnf', return_value= mock_libdnf): package = libdnf.Package() package.update(packages, advisories) #strip the evrs out of the package mock_libdnf.upgrade.assert_called_with(packages)
Katello/katello-agent
test/test_katello/test_agent/test_pulp/test_libdnf.py
Python
gpl-2.0
1,456
package com.ag.common.http.builder; import com.ag.common.http.request.PostFileRequest; import com.ag.common.http.request.RequestCall; import java.io.File; import java.util.LinkedHashMap; import java.util.Map; import okhttp3.MediaType; public class PostFileBuilder extends OkHttpRequestBuilder { private File file; private MediaType mediaType; public OkHttpRequestBuilder file(File file) { this.file = file; return this; } public OkHttpRequestBuilder mediaType(MediaType mediaType) { this.mediaType = mediaType; return this; } @Override public RequestCall build() { return new PostFileRequest(url, tag, params, headers, file, mediaType).build(); } @Override public PostFileBuilder url(String url) { this.url = url; return this; } @Override public PostFileBuilder tag(Object tag) { this.tag = tag; return this; } @Override public PostFileBuilder headers(Map<String, String> headers) { this.headers = headers; return this; } @Override public PostFileBuilder addHeader(String key, String val) { if (this.headers == null) { headers = new LinkedHashMap<>(); } headers.put(key, val); return this; } }
ZhanJohn/AG_Modules
ag_common/src/main/java/com/ag/common/http/builder/PostFileBuilder.java
Java
gpl-2.0
1,360
# config/unicorn.rb worker_processes Integer(ENV["WEB_CONCURRENCY"] || 3) timeout 35 preload_app true before_fork do |server, worker| Signal.trap 'TERM' do puts 'Unicorn master intercepting TERM and sending myself QUIT instead' Process.kill 'QUIT', Process.pid end defined?(ActiveRecord::Base) and ActiveRecord::Base.connection.disconnect! end after_fork do |server, worker| Signal.trap 'TERM' do puts 'Unicorn worker intercepting TERM and doing nothing. Wait for master to send QUIT' end defined?(ActiveRecord::Base) and ActiveRecord::Base.establish_connection end
bl4ckdu5t/vitabiotics
config/unicorn.rb
Ruby
gpl-2.0
602
<?php $this->currencies = array ( 'adp' => 'Andorran Peseta', 'aed' => 'United Arab Emirates Dirham', 'afa' => 'Afghani (1927-2002)', 'afn' => 'Afghani', 'all' => 'Albanian Lek', 'amd' => 'Armenian Dram', 'ang' => 'Netherlands Antillan Guilder', 'aoa' => 'Angolan Kwanza', 'aok' => 'Angolan Kwanza (1977-1990)', 'aon' => 'Angolan New Kwanza (1990-2000)', 'aor' => 'Angolan Kwanza Reajustado (1995-1999)', 'ara' => 'Argentine Austral', 'arp' => 'Argentine Peso (1983-1985)', 'ars' => 'Argentine Peso', 'ats' => 'Austrian Schilling', 'aud' => 'Australian Dollar', 'awg' => 'Aruban Guilder', 'azm' => 'Azerbaijanian Manat', 'bad' => 'Bosnia-Herzegovina Dinar', 'bam' => 'Bosnia-Herzegovina Convertible Mark', 'bbd' => 'Barbados Dollar', 'bdt' => 'Bangladesh Taka', 'bec' => 'Belgian Franc (convertible)', 'bef' => 'Belgian Franc', 'bel' => 'Belgian Franc (financial)', 'bgl' => 'Bulgarian Hard Lev', 'bgn' => 'Bulgarian New Lev', 'bhd' => 'Bahraini Dinar', 'bif' => 'Burundi Franc', 'bmd' => 'Bermudan Dollar', 'bnd' => 'Brunei Dollar', 'bob' => 'Boliviano', 'bop' => 'Bolivian Peso', 'bov' => 'Bolivian Mvdol', 'brb' => 'Brazilian Cruzeiro Novo (1967-1986)', 'brc' => 'Brazilian Cruzado', 'bre' => 'Brazilian Cruzeiro (1990-1993)', 'brl' => 'Brazilian Real', 'brn' => 'Brazilian Cruzado Novo', 'brr' => 'Brazilian Cruzeiro', 'bsd' => 'Bahamian Dollar', 'btn' => 'Bhutan Ngultrum', 'buk' => 'Burmese Kyat', 'bwp' => 'Botswanan Pula', 'byb' => 'Belarussian New Ruble (1994-1999)', 'byr' => 'Belarussian Ruble', 'bzd' => 'Belize Dollar', 'cad' => 'Canadian Dollar', 'cdf' => 'Congolese Franc Congolais', 'che' => 'WIR Euro', 'chf' => 'Swiss Franc', 'chw' => 'WIR Franc', 'clf' => 'Chilean Unidades de Fomento', 'clp' => 'Chilean Peso', 'cny' => 'Chinese Yuan Renminbi', 'cop' => 'Colombian Peso', 'cou' => 'Unidad de Valor Real', 'crc' => 'Costa Rican Colon', 'csd' => 'Serbian Dinar', 'csk' => 'Czechoslovak Hard Koruna', 'cup' => 'Cuban Peso', 'cve' => 'Cape Verde Escudo', 'cyp' => 'Cyprus Pound', 'czk' => 'Czech Republic Koruna', 'ddm' => 'East German Ostmark', 'dem' => 'Deutsche Mark', 'djf' => 'Djibouti Franc', 'dkk' => 'Danish Krone', 'dop' => 'Dominican Peso', 'dzd' => 'Algerian Dinar', 'ecs' => 'Ecuador Sucre', 'ecv' => 'Ecuador Unidad de Valor Constante (UVC)', 'eek' => 'Estonian Kroon', 'egp' => 'Egyptian Pound', 'eqe' => 'Ekwele', 'ern' => 'Eritrean Nakfa', 'esa' => 'Spanish Peseta (A account)', 'esb' => 'Spanish Peseta (convertible account)', 'esp' => 'Spanish Peseta', 'etb' => 'Ethiopian Birr', 'eur' => 'Euro', 'fim' => 'Finnish Markka', 'fjd' => 'Fiji Dollar', 'fkp' => 'Falkland Islands Pound', 'frf' => 'French Franc', 'gbp' => 'British Pound Sterling', 'gek' => 'Georgian Kupon Larit', 'gel' => 'Georgian Lari', 'ghc' => 'Ghana Cedi', 'gip' => 'Gibraltar Pound', 'gmd' => 'Gambia Dalasi', 'gnf' => 'Guinea Franc', 'gns' => 'Guinea Syli', 'gqe' => 'Equatorial Guinea Ekwele Guineana', 'grd' => 'Greek Drachma', 'gtq' => 'Guatemala Quetzal', 'gwe' => 'Portuguese Guinea Escudo', 'gwp' => 'Guinea-Bissau Peso', 'gyd' => 'Guyana Dollar', 'hkd' => 'Hong Kong Dollar', 'hnl' => 'Hoduras Lempira', 'hrd' => 'Croatian Dinar', 'hrk' => 'Croatian Kuna', 'htg' => 'Haitian Gourde', 'huf' => 'Hungarian Forint', 'idr' => 'Indonesian Rupiah', 'iep' => 'Irish Pound', 'ilp' => 'Israeli Pound', 'ils' => 'Israeli New Sheqel', 'inr' => 'Indian Rupee', 'iqd' => 'Iraqi Dinar', 'irr' => 'Iranian Rial', 'isk' => 'Icelandic Krona', 'itl' => 'Italian Lira', 'jmd' => 'Jamaican Dollar', 'jod' => 'Jordanian Dinar', 'jpy' => 'Japanese Yen', 'kes' => 'Kenyan Shilling', 'kgs' => 'Kyrgystan Som', 'khr' => 'Cambodian Riel', 'kmf' => 'Comoro Franc', 'kpw' => 'North Korean Won', 'krw' => 'South Korean Won', 'kwd' => 'Kuwaiti Dinar', 'kyd' => 'Cayman Islands Dollar', 'kzt' => 'Kazakhstan Tenge', 'lak' => 'Laotian Kip', 'lbp' => 'Lebanese Pound', 'lkr' => 'Sri Lanka Rupee', 'lrd' => 'Liberian Dollar', 'lsl' => 'Lesotho Loti', 'lsm' => 'Maloti', 'ltl' => 'Lithuanian Lita', 'ltt' => 'Lithuanian Talonas', 'luc' => 'Luxembourg Convertible Franc', 'luf' => 'Luxembourg Franc', 'lul' => 'Luxembourg Financial Franc', 'lvl' => 'Latvian Lats', 'lvr' => 'Latvian Ruble', 'lyd' => 'Libyan Dinar', 'mad' => 'Moroccan Dirham', 'maf' => 'Moroccan Franc', 'mdl' => 'Moldovan Leu', 'mga' => 'Madagascar Ariary', 'mgf' => 'Madagascar Franc', 'mkd' => 'Macedonian Denar', 'mlf' => 'Mali Franc', 'mmk' => 'Myanmar Kyat', 'mnt' => 'Mongolian Tugrik', 'mop' => 'Macao Pataca', 'mro' => 'Mauritania Ouguiya', 'mtl' => 'Maltese Lira', 'mtp' => 'Maltese Pound', 'mur' => 'Mauritius Rupee', 'mvr' => 'Maldive Islands Rufiyaa', 'mwk' => 'Malawi Kwacha', 'mxn' => 'Mexican Peso', 'mxp' => 'Mexican Silver Peso (1861-1992)', 'mxv' => 'Mexican Unidad de Inversion (UDI)', 'myr' => 'Malaysian Ringgit', 'mze' => 'Mozambique Escudo', 'mzm' => 'Mozambique Metical', 'nad' => 'Namibia Dollar', 'ngn' => 'Nigerian Naira', 'nic' => 'Nicaraguan Cordoba', 'nio' => 'Nicaraguan Cordoba Oro', 'nlg' => 'Netherlands Guilder', 'nok' => 'Norwegian Krone', 'npr' => 'Nepalese Rupee', 'nzd' => 'New Zealand Dollar', 'omr' => 'Oman Rial', 'pab' => 'Panamanian Balboa', 'pei' => 'Peruvian Inti', 'pen' => 'Peruvian Sol Nuevo', 'pes' => 'Peruvian Sol', 'pgk' => 'Papua New Guinea Kina', 'php' => 'Philippine Peso', 'pkr' => 'Pakistan Rupee', 'pln' => 'Polish Zloty', 'plz' => 'Polish Zloty (1950-1995)', 'pte' => 'Portuguese Escudo', 'pyg' => 'Paraguay Guarani', 'qar' => 'Qatari Rial', 'rhd' => 'Rhodesian Dollar', 'rol' => 'Romanian Leu', 'ron' => 'Romanian Leu', 'rub' => 'Russian Ruble', 'rur' => 'Russian Ruble (1991-1998)', 'rwf' => 'Rwandan Franc', 'sar' => 'Saudi Riyal', 'sbd' => 'Solomon Islands Dollar', 'scr' => 'Seychelles Rupee', 'sdd' => 'Sudanese Dinar', 'sdp' => 'Sudanese Pound', 'sek' => 'Swedish Krona', 'sgd' => 'Singapore Dollar', 'shp' => 'Saint Helena Pound', 'sit' => 'Slovenia Tolar', 'skk' => 'Slovak Koruna', 'sll' => 'Sierra Leone Leone', 'sos' => 'Somali Shilling', 'srd' => 'Surinam Dollar', 'srg' => 'Suriname Guilder', 'std' => 'Sao Tome and Principe Dobra', 'sur' => 'Soviet Rouble', 'svc' => 'El Salvador Colon', 'syp' => 'Syrian Pound', 'szl' => 'Swaziland Lilangeni', 'thb' => 'Thai Baht', 'tjr' => 'Tajikistan Ruble', 'tjs' => 'Tajikistan Somoni', 'tmm' => 'Turkmenistan Manat', 'tnd' => 'Tunisian Dinar', 'top' => 'Tonga Paʻanga', 'tpe' => 'Timor Escudo', 'trl' => 'Turkish Lira', 'try' => 'New Turkish Lira', 'ttd' => 'Trinidad and Tobago Dollar', 'twd' => 'Taiwan New Dollar', 'tzs' => 'Tanzanian Shilling', 'uah' => 'Ukrainian Hryvnia', 'uak' => 'Ukrainian Karbovanetz', 'ugs' => 'Ugandan Shilling (1966-1987)', 'ugx' => 'Ugandan Shilling', 'usd' => 'US Dollar', 'usn' => 'US Dollar (Next day)', 'uss' => 'US Dollar (Same day)', 'uyp' => 'Uruguay Peso (1975-1993)', 'uyu' => 'Uruguay Peso Uruguayo', 'uzs' => 'Uzbekistan Sum', 'veb' => 'Venezuelan Bolivar', 'vnd' => 'đồng', 'vuv' => 'Vanuatu Vatu', 'wst' => 'Western Samoa Tala', 'xaf' => 'CFA Franc BEAC', 'xag' => 'Silver', 'xau' => 'Gold', 'xba' => 'European Composite Unit', 'xbb' => 'European Monetary Unit', 'xbc' => 'European Unit of Account (XBC)', 'xbd' => 'European Unit of Account (XBD)', 'xcd' => 'East Caribbean Dollar', 'xdr' => 'Special Drawing Rights', 'xeu' => 'European Currency Unit', 'xfo' => 'French Gold Franc', 'xfu' => 'French UIC-Franc', 'xof' => 'CFA Franc BCEAO', 'xpd' => 'Palladium', 'xpf' => 'CFP Franc', 'xpt' => 'Platinum', 'xre' => 'RINET Funds', 'xts' => 'Testing Currency Code', 'xxx' => 'No Currency', 'ydd' => 'Yemeni Dinar', 'yer' => 'Yemeni Rial', 'yud' => 'Yugoslavian Hard Dinar', 'yum' => 'Yugoslavian Noviy Dinar', 'yun' => 'Yugoslavian Convertible Dinar', 'zal' => 'South African Rand (financial)', 'zar' => 'South African Rand', 'zmk' => 'Zambian Kwacha', 'zrn' => 'Zairean New Zaire', 'zrz' => 'Zairean Zaire', 'zwd' => 'Zimbabwe Dollar', );
prdatur/soopfw
language/currencies/vi.php
PHP
gpl-2.0
8,370
<?php /** * @package AcyMailing for Joomla! * @version 4.5.0 * @author acyba.com * @copyright (C) 2009-2013 ACYBA S.A.R.L. All rights reserved. * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ defined('_JEXEC') or die('Restricted access'); ?><?php jimport( 'joomla.html.parameter' ); class acymailingView extends JView{ } class acymailingControllerCompat extends JController{ } function acymailing_loadResultArray(&$db){ return $db->loadResultArray(); } function acymailing_loadMootools($loadMootoolsMoreLib = false){ JHTML::_('behavior.mootools'); } function acymailing_getColumns($table){ $db = JFactory::getDBO(); $allfields = $db->getTableFields($table); return reset($allfields); } function acymailing_getEscaped($value, $extra = false) { $db = JFactory::getDBO(); return $db->getEscaped($value, $extra); } function acymailing_getFormToken() { return JUtility::getToken(); } if(!class_exists('acyParameter')){ class acyParameter extends JParameter{} }
QuyICDAC/icdacgov
administrator/components/com_acymailing/compat/compat1.php
PHP
gpl-2.0
1,044
/* * WordPress.com MetaDNS */ #ifndef __H_WPMETABACKEND_HH__ #define __H_WPMETABACKEND_HH__ #include <cstring> #include <vector> #include <random> #include <map> #include <chrono> #include <pdns/namespaces.hh> #include <pdns/dnsbackend.hh> #include <pdns/dnspacket.hh> #include "defines.h" #include "database.hh" #include "hashring.hh" #include "hashcache.hh" #include "poolcache.hh" #include "cache.hh" typedef std::mt19937 oRandom; std::uniform_int_distribution<uint32_t> uint_dist; struct Vec_Sorter { bool operator()( const std::vector<string>& lhs, const std::vector<string>& rhs ) { return ( lhs[VEC_random_value] < rhs[VEC_random_value] ); } }; class WPMetaBackend : public DNSBackend { public: WPMetaBackend( const string &suffix = "" ); ~WPMetaBackend(); WPMetaBackend *parent; void lookup( const QType &qtype, const string &domain_name, DNSPacket *packet = NULL, int domain_id = -1 ); bool list( const string &target, int domain_id ); bool get( DNSResourceRecord &r ); bool getSOA( const string &domain_name, SOAData &soadata, DNSPacket* packet ); private: Database *m_db; Hash_Cache m_HC; Pool_Cache m_PC; Cache<std::string, SOA> m_SC; Cache<std::string, Records> m_RC; Cache<std::string, Lookup> m_LC; vector<vector<std::string> > m_results; oRandom m_random; string m_qname; string m_origin; uint32_t m_cache_purge_counter; int query_db( const string& p_sql ); int query_db( const string& p_sql, Database::result_t& result ); bool prepare_records( const string& query_domain, const Database::result_t& p_results ); void send_from_hash_cache( const uint64_t& pool_house_id, const std::string& query_domain, const Database::row_t& rrow ); void send_from_pool_cache( const uint64_t& pool_house_id, const Database::row_t& rrow ); bool serve_from_cache( const string& lcase_domain_name, const string& lcase_org_query ); string build_sql_from_lookup_cache( string sqlfields ); }; #endif // __H_WPMETABACKEND_HH__
Automattic/metadns
src/wpmetabackend.hh
C++
gpl-2.0
1,972
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Colecciones")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Colecciones")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c2b407e5-79b2-49c4-8317-6b802d5b7a42")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
UNAH-SISTEMAS/2015.3.oop
4_Colecciones/Colecciones/Properties/AssemblyInfo.cs
C#
gpl-2.0
1,398
<?php /** * @file * Hooks provided by Requirement Dashboard. */ /** * Add requirement dashboards to be created * * Allows other modules to create providers for requirement dashboards * */ function hook_requirement_dashboard_provider() { // this is the machine name used on permissions page / elsewhere $dashboards['provider_name'] = array( // required: name of the module invoking this 'title' => 'Title of the Dashboard', // required: menu path for accessing this 'path' => 'pathname', ); // you can define as many providers as you want though including only 1 is more modular $dashboards['og'] = array( 'title' => 'Group Status', 'path' => 'node/%node/og_status', ); return $dashboards; } /** * Implements hook_requirement_dashboard_provider_alter(). */ function hook_requirement_dashboard_provider_alter(&$dashboards) { } /** * Add requirments to dashboard providers * * Allows other modules to define requirements * Valid severities are: * REQUIREMENT_INFO * REQUIREMENT_OK * REQUIREMENT_WARNING * REQUIREMENT_ERROR * */ function hook_dashboard_requirements($provider) { // always include a switch statement with each case being the name of a provider switch ($provider) { case 'provider': // something to make this info dynamic $calculated_value = 'something dynamic'; // you can define requirements much like the core requirements hook $requirements['requirement_name'] = array( // required: The title to appear in the first column 'title' => t('Title'), // required: The value to display in the 2nd column, most likely something variable 'value' => $calculated_value, // required: The class that should be applied, this should be calculated in most instances 'severity' => REQUIREMENT_INFO, ); break; case 'og': // example requirement from the group provider $group = og_group_get_context(); $requirements['name'] = array( 'title' => t('Group Name'), 'value' => $group->title, 'severity' => REQUIREMENT_INFO, ); break; } return $requirements; } /** * Implements hook_dashboard_requirements_alter(). */ function hook_dashboard_requirements_alter(&$requirements, $provider) { }
eleonel/Drupaltech
profiles/elms/modules/contrib/requirement_dashboard/requirement_dashboard.api.php
PHP
gpl-2.0
2,304
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace proyectoprogra { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
Axel030/ProyectoFinal
proyectoprogra/proyectoprogra/Program.cs
C#
gpl-2.0
515
<html> <head> <title>How to make a 3D sphere with HTML5</title> <script src="js/buildIcoSphere.js"> </script> <script src="js/render.js"> </script> <style type="text/css"> canvas { border: 4px solid #A0A0A0; background: white; display: block; } </style> </head> <body onload="init();"> <canvas id="sphere3d" width="500" height="500"> You don't have canvas </canvas> <fieldset> <legend>Initial Size</legend> <p> <input type = "radio" name = "radSize" id = "sizeSmall" value = "4" checked = "checked" /> <label for = "sizeSmall">4 Points</label><br/> <input type = "radio" name = "radSize" id = "sizeMed" value = "5" /> <label for = "sizeMed">5 Points</label><br/> <input type = "radio" name = "radSize" id = "sizeLarge" value = "6" /> <label for = "sizeLarge">6 Points</label><br/> <input type = "radio" name = "radSize" id = "ico" value = "12" /> <label for = "sizeLarge">12 Points</label><br/> <input type = "radio" name = "radSize" id = "cus" value = "custom" /> <label for = "sizeLarge">Custom</label> <input id="cust" type="number" min="4" oninput="setInValue('cus',1)" /> </p> </fieldset> <br/> Division Tollerance <input id="tol" type="number" min="1" step="0.1" value="1.3" max="3" oninput="setInput('tol')"/><br/> # of Simulations <input id="sim" type="number" min="1" step="1" value="300" max="10000" oninput="setInput('sim')"/><br/> Distance Tiny<input id="dist" type="range" max="10" oninput="setInValue('dist')" />Big <span id="distVal"></span><br/> Rotation Speed Fast<input id="rota" type="range" step="10" oninput="setInValue('rota')"/>Slow <span id="rotaVal"></span><br/> Point Size Small<input id="siz" type="range" min="1" max="5" step="0.5" oninput="setInValue('siz')"/>Big <span id="sizVal"></span><br/> <label for="divi">Divide Sphere </label><input id="divi" type="number" min="1" max="5" step="1" value ="1" oninput="divideSphereClick()"/><br/> <input type="button" id="col" value="Reset Colors" onclick="resetColor()"> <p> To controll the sphere by mouse double click anywhere on the document and then start moving the mouse. Doubleclick again to stop </p> <p>Stats</p> <p id="stats"></p> </body> </html>
mareklspak/spak.io_logo
sphere.html
HTML
gpl-2.0
2,802
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>PHPXRef 0.7.1 : Unnamed Project : Variable Reference: $thumb_quality</title> <link rel="stylesheet" href="../sample.css" type="text/css"> <link rel="stylesheet" href="../sample-print.css" type="text/css" media="print"> <style id="hilight" type="text/css"></style> <meta http-equiv="content-type" content="text/html;charset=iso-8859-1"> </head> <body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff"> <table class="pagetitle" width="100%"> <tr> <td valign="top" class="pagetitle"> [ <a href="../index.html">Index</a> ] </td> <td align="right" class="pagetitle"> <h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2> </td> </tr> </table> <!-- Generated by PHPXref 0.7.1 at Sat Nov 21 22:13:19 2015 --> <!-- PHPXref (c) 2000-2010 Gareth Watts - gareth@omnipotent.net --> <!-- http://phpxref.sourceforge.net/ --> <script src="../phpxref.js" type="text/javascript"></script> <script language="JavaScript" type="text/javascript"> <!-- ext='.html'; relbase='../'; subdir='_variables'; filename='index.html'; cookiekey='phpxref'; handleNavFrame(relbase, subdir, filename); logVariable('thumb_quality'); // --> </script> <script language="JavaScript" type="text/javascript"> if (gwGetCookie('xrefnav')=='off') document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>'); else document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>'); </script> <noscript> <p class="navlinks"> [ <a href="../nav.html" target="_top">Show Explorer</a> ] [ <a href="index.html" target="_top">Hide Navbar</a> ] </p> </noscript> [<a href="../index.html">Top level directory</a>]<br> <script language="JavaScript" type="text/javascript"> <!-- document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>'); document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">'); document.writeln('<tr><td class="searchbox-title">'); document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>'); document.writeln('<\/td><\/tr>'); document.writeln('<tr><td class="searchbox-body" id="searchbox-body">'); document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>'); document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: '); document.writeln('<input type="text" size=10 value="" name="classname"><br>'); document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: '); document.writeln('<input type="text" size=10 value="" name="funcname"><br>'); document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: '); document.writeln('<input type="text" size=10 value="" name="varname"><br>'); document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: '); document.writeln('<input type="text" size=10 value="" name="constname"><br>'); document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: '); document.writeln('<input type="text" size=10 value="" name="tablename"><br>'); document.writeln('<input type="submit" class="searchbox-button" value="Search">'); document.writeln('<\/form>'); document.writeln('<\/td><\/tr><\/table>'); document.writeln('<\/td><\/tr><\/table>'); // --> </script> <div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div> <h3>Variable Cross Reference</h3> <h2><a href="index.html#thumb_quality">$thumb_quality</a></h2> <b>Defined at:</b><ul> <li><a href="../inc/files/model/_file.funcs.php.html">/inc/files/model/_file.funcs.php</A> -> <a href="../inc/files/model/_file.funcs.php.source.html#l1649"> line 1649</A></li> <li><a href="../inc/files/model/_file.class.php.html">/inc/files/model/_file.class.php</A> -> <a href="../inc/files/model/_file.class.php.source.html#l2527"> line 2527</A></li> </ul> <br><b>Referenced 7 times:</b><ul> <li><a href="../htsrv/getfile.php.html">/htsrv/getfile.php</a> -> <a href="../htsrv/getfile.php.source.html#l123"> line 123</a></li> <li><a href="../htsrv/getfile.php.html">/htsrv/getfile.php</a> -> <a href="../htsrv/getfile.php.source.html#l160"> line 160</a></li> <li><a href="../inc/files/model/_file.funcs.php.html">/inc/files/model/_file.funcs.php</a> -> <a href="../inc/files/model/_file.funcs.php.source.html#l1649"> line 1649</a></li> <li><a href="../inc/files/model/_file.funcs.php.html">/inc/files/model/_file.funcs.php</a> -> <a href="../inc/files/model/_file.funcs.php.source.html#l1698"> line 1698</a></li> <li><a href="../inc/files/model/_file.class.php.html">/inc/files/model/_file.class.php</a> -> <a href="../inc/files/model/_file.class.php.source.html#l2527"> line 2527</a></li> <li><a href="../inc/files/model/_file.class.php.html">/inc/files/model/_file.class.php</a> -> <a href="../inc/files/model/_file.class.php.source.html#l2536"> line 2536</a></li> <li><a href="../inc/files/model/_file.class.php.html">/inc/files/model/_file.class.php</a> -> <a href="../inc/files/model/_file.class.php.source.html#l2545"> line 2545</a></li> </ul> <!-- A link to the phpxref site in your customized footer file is appreciated ;-) --> <br><hr> <table width="100%"> <tr><td>Generated: Sat Nov 21 22:13:19 2015</td> <td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td> </tr> </table> </body></html>
mgsolipa/b2evolution_phpxref
_variables/thumb_quality.html
HTML
gpl-2.0
5,923
#!/usr/bin/python # -*- coding: utf-8 -*- import urllib, urllib2 import xbmcplugin, xbmcaddon, xbmcgui, xbmc import sys, os, re, json, base64, operator, datetime, time from resources.local import * pluginhandle = int(sys.argv[1]) addon = xbmcaddon.Addon() settings = xbmcaddon.Addon( id = "plugin.video.tele.ml" ) domain = base64.b64decode(settings.getSetting("domain")) icon_path = os.path.join(xbmc.translatePath(os.path.join(xbmc.translatePath(os.path.join(xbmc.translatePath(os.path.join("special://","home")),"addons")),"plugin.video.tele.ml")),"icon.png") def parameters_string_to_dict(parameters): paramDict = {} if parameters: paramPairs = parameters[1:].split("&") for paramsPair in paramPairs: paramSplits = paramsPair.split('=') if (len(paramSplits)) == 2: paramDict[paramSplits[0]] = paramSplits[1] return paramDict def translation(id): return addon.getLocalizedString(id).encode('utf-8','ignore') def get_list(query,data): req = urllib2.Request(domain+'api-json-33/'+query+'.php') f = urllib2.urlopen(req,data) html = f.read() f.close() return html def info_display(channel_info): if ";;;" in channel_info: channel_display = "" nb_line = 0 nb_content = int(float(settings.getSetting("nb_epg_program"))) get_timezone = datetime.datetime.utcnow() - datetime.datetime.now() prog_list = channel_info.split(';;;') prog_list.pop() for prog in prog_list: prog_data = prog.split(';;') progtime = datetime.datetime.fromtimestamp(time.mktime(time.strptime(prog_data[0],"%Y-%m-%d %H:%M:%S"))) displaytime = progtime - get_timezone if ( displaytime > datetime.datetime.now() ) : if ( nb_line < nb_content-1 ): channel_display += displaytime.strftime("%H:%M")+" - "+prog_data[1]+"[CR]" nb_line += 1 else: channel_display = "[B]"+displaytime.strftime("%H:%M")+" - "+prog_data[1]+"[/B][CR]" return channel_display.replace("\\", "") else: return channel_info.replace("\\", "") def addDir(name, url, mode, iconimage, fanart, desc=""): u = sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode) xbmcplugin.addSortMethod(pluginhandle, sortMethod=xbmcplugin.SORT_METHOD_LABEL) ok = True liz = xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage) if ( fanart != '' ): liz.setProperty("Fanart_Image", fanart) liz.setInfo(type="Video", infoLabels={"Title": name, "Plot": desc}) ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=True) return ok def categories(mode,url,path,img): hide_adult = ( settings.getSetting( "hide_adult" ) == "true" ) empty_category = ( settings.getSetting( "empty_category" ) == "true" ) data_list = json.loads(get_list(mode,urllib.urlencode({'hide_adult': hide_adult,'empty_category': empty_category}))) if (len(data_list) > 0): for (category_id, category_info) in data_list.items(): add_category(category_info[0], category_id, url, domain+'images/'+path+'/'+category_id+'.'+img, domain+'images/channels/'+category_info[3]+'.jpg', category_info[4], category_info[2], category_info[1]) xbmcplugin.endOfDirectory(pluginhandle) def add_category(name, url, mode, iconimage, fanart, working, nb_channels, desc=""): u = sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode) xbmcplugin.addSortMethod(pluginhandle, sortMethod=xbmcplugin.SORT_METHOD_LABEL) ok = True if (working == 0): name = name+" | "+translation(30023) liz = xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage) if ( fanart != '' ): liz.setProperty("Fanart_Image", fanart) liz.setInfo(type="Video", infoLabels={"Title": name, "Plot": desc, "Genre": str(nb_channels)+" "+translation(30003)}) ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=True) return ok def channels(mode,url): hide_adult = ( settings.getSetting( "hide_adult" ) == "true" ) broken_channel = ( settings.getSetting( "broken_channel" ) == "true" ) epg_display = ( settings.getSetting( "epg_display" ) == "true" ) data_list = json.loads(get_list(mode,urllib.urlencode({'content_id': url, 'hide_adult': hide_adult, 'broken_channel': broken_channel, 'epg_display': epg_display}))) if (len(data_list) > 0): sorted_data_list = sorted(data_list.items(), key=lambda k: int(k[0])) for (channel_info) in (sorted_data_list): add_channel(channel_info[1][0], channel_info[1][2], 'sources', domain+'images/channels/'+channel_info[1][2]+'.png', domain+'images/channels/'+channel_info[1][2]+'.jpg', "", channel_info[1][3], channel_info[1][4], channel_info[1][1]) xbmcplugin.endOfDirectory(pluginhandle) def add_channel(name, url, mode, iconimage, fanart, channel_nb, genre, working, desc=""): u = sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode) xbmcplugin.addSortMethod(pluginhandle, sortMethod=xbmcplugin.SORT_METHOD_UNSORTED) xbmcplugin.addSortMethod(pluginhandle, sortMethod=xbmcplugin.SORT_METHOD_LABEL) ok = True if (working == 0): name = name+" | "+translation(30023) liz = xbmcgui.ListItem(name.replace("\\", ""), iconImage=iconimage, thumbnailImage=iconimage) if ( fanart != '' ): liz.setProperty("Fanart_Image", fanart) liz.setInfo(type="Video", infoLabels={"Title": name.replace("\\", ""), "Plot": info_display(desc), "Genre": genre}) ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=False) return ok def sources(mode,url): source_list = [] display_list = [] broken_stream = ( settings.getSetting( "broken_stream" ) == "true" ) geo_block = ( settings.getSetting( "geo_block" ) == "true" ) ext_player = ( settings.getSetting( "ext_player" ) == "true" ) decay_stream = ( settings.getSetting( "decay_stream" ) == "true" ) email = settings.getSetting( "email" ) password = settings.getSetting( "password" ) data_list = json.loads(get_list(mode,urllib.urlencode({'channel_id': url, 'broken_stream': broken_stream, 'geo_block': geo_block, 'ext_player': ext_player, 'decay_stream': decay_stream, 'email': email, 'password': password}))) if (len(data_list) > 0): dialog = xbmcgui.Dialog() try: for (source_id, source_info) in sorted(data_list.items(), key=operator.itemgetter(1), reverse=True): source_list.append(source_id) stream_txt = str(source_info[0])+" px | "+source_info[1].upper() if ( source_info[3] != 'no' ): stream_txt = stream_txt+" | "+source_info[3].upper()+" "+translation(30019) if ( int(source_info[4]) != 0 ): if (int (source_info[4]) > 24): stream_txt = stream_txt+" | +"+str(int(source_info[4])/24)+" "+translation(30024) else: stream_txt = stream_txt+" | +"+source_info[4]+" "+translation(30020) if ( source_info[5] != 'no' ): stream_txt = stream_txt+" | "+translation(30021) if ( source_info[2] == 'no' ): stream_txt = stream_txt+" | "+translation(30022) display_list.append(stream_txt) stream_url = source_info[6] video_source = dialog.select(translation(30007), display_list) if (not video_source == -1 ): play_video("play_video", source_list[video_source],stream_url) except: xbmcgui.Dialog().ok(translation(30017), '[B]'+translation(30030)+'...[/B]', translation(30029)) def play_video(mode,stream_id,stream_url): xbmc.executebuiltin("XBMC.Notification(%s,%s,%s,%s)" % (translation(30017),translation(30018)+'...',3000,icon_path)) data_list = json.loads(get_list(mode,urllib.urlencode({'stream_id': stream_id, 'stream_url': stream_url}))) if (len(data_list) > 0): for (stream_id, stream_info) in data_list.items(): liz = xbmcgui.ListItem(stream_info[1], iconImage=domain+'images/channels/'+stream_info[2]+'.png', thumbnailImage=domain+'images/channels/'+stream_info[2]+'.png') xbmc.Player( xbmc.PLAYER_CORE_MPLAYER ).play(url_convert(stream_info[0]),listitem=liz) params = parameters_string_to_dict(sys.argv[2]) mode = urllib.unquote_plus(params.get('mode', '')) url = urllib.unquote_plus(params.get('url', '')) name = urllib.unquote_plus(params.get('name', '')) if mode == 'play_video': play_video(mode,url) elif mode == 'sources': sources(mode,url) elif mode == 'channel_cont': channels(mode,url) elif mode == 'channel_coun': channels(mode,url) elif mode == 'channel_count': channels(mode,url) elif mode == 'category': categories('category','channel_cont','contents','jpg') elif mode == 'country': categories('country','channel_coun','countries','png') elif mode == 'langage': categories('language','channel_count','languages','png') elif mode == 'channel_all': channels('channel_all',"") else: channel_display = ( int(settings.getSetting("category")) ) if channel_display == 0: categories('category','channel_cont','contents','jpg') elif channel_display == 1: categories('country','channel_coun','countries','png') elif channel_display == 2: categories('language','channel_count','languages','png') else: channels('channel_all',"")
idi2019/plugin.video.tele.ml
default.py
Python
gpl-2.0
9,683
from sdssgaussfitter import gaussfit import numpy as np import os,sys from util import utils from util.readDict import readDict from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt def aperture(startpx,startpy,radius=7): r = radius length = 2*r height = length allx = xrange(startpx-int(np.ceil(length/2.0)),startpx+int(np.floor(length/2.0))+1) ally = xrange(startpy-int(np.ceil(height/2.0)),startpy+int(np.floor(height/2.0))+1) pixx = [] pixy = [] mask=np.ones((46,44)) for x in allx: for y in ally: if (np.abs(x-startpx))**2+(np.abs(y-startpy))**2 <= (r)**2 and 0 <= y and y < 46 and 0 <= x and x < 44: mask[y,x]=0. return mask #def gaussian(height, center_x, center_y, width_x, width_y,offset): # """Returns a gaussian function with the given parameters""" # width_x = float(width_x) # width_y = float(width_y) # return lambda x,y: height*np.exp(-(((center_x-x)/width_x)**2+((center_y-y)/width_y)**2)/2)+offset #testy = np.array([[gaussian(2,10,10,3,3,5)(x,y) for y in range(46)] for x in range(44)]) #utils.plotArray(testy,cbar=True) param = readDict() #param.read_from_file('G158-100params.dict') #param.read_from_file('pg0220params.dict') #param.read_from_file('landolt9542params.dict') #param.read_from_file('corot18params.dict') if len(sys.argv)<2: print "Provide file name to fit. Syntax >>python fitPsf.py objectparams.dict [filenumber]" sys.exit(1) #read in parameter file as command line argument param.read_from_file(sys.argv[1]) #provide optional file number if the object in the param file has alternate .npz files to be specified individually fileNum = None if len(sys.argv)>2: fileNum = "_"+str(sys.argv[2]) npzLoadFile = param['npzLoadFile'] npzfitpsf = param['npzfitpsf'] giffitpsf = param['giffitpsf'] if fileNum != None: npzLoadFile = npzLoadFile.split('.')[0]+fileNum+'.'+npzLoadFile.split('.')[1] npzfitpsf = npzfitpsf.split('.')[0]+fileNum+'.'+npzfitpsf.split('.')[1] giffitpsf = giffitpsf.split('.')[0]+fileNum+'.'+giffitpsf.split('.')[1] FramesPerFile = param['FramesPerFile'] #NumFiles = param['NumFiles'] #for filenum in range(len(NumFiles)): # if NumFiles[filenum] > 0: # NumFiles[filenum] = NumFiles[filenum]*FramesPerFile #NumFrames = NumFiles NumFrames = 31 print "There should be this many frames: ", NumFrames guessX = param['guessX'][0] guessY = param['guessY'][0] stackDict = np.load(npzLoadFile) stack = stackDict['stack'] wvls = stackDict['wvls'] print "The file actually has this many: ", len(wvls) paramsList = [] errorsList = [] fitImgList = [] chisqList = [] plt.ion() for iFrame in range(0,np.shape(stack)[0]): frame = stack[iFrame,:,:] #print "Frame max= ", np.nanmax(frame,axis=None) #frame *= CorrFactors #print "Corrected Frame max= ", np.nanmax(frame,axis=None) nanMask = np.isnan(frame) #for interval in xrange(len(NumFrames)-1): # if NumFrames[interval] != NumFrames[interval+1]: # if NumFrames[interval] < iFrame <= NumFrames[interval+1]: # guessX = guessX[interval] # guessY = guessY[interval] # print guessX, guessY ''' apertureMask = aperture(guessX,guessY,radius=4) err = np.sqrt(frame) #divide by 2 to constrain PSF fit even tighter to avoid fitting to wrong peak if PSF is divided by dead pixels err[frame > 100]=np.inf #err[frame<10] = 100 frame[nanMask] = 0 #set to finite value that will be ignored err[nanMask] = np.inf #ignore these data points err[frame==0] = np.inf err[apertureMask==1] = 1.0 #np.sqrt(frame[apertureMask==1])/2.0 #weight points closer to the expected psf higher nearDeadCutoff = 1 #100/15 cps for 4000-6000 angstroms err[frame<nearDeadCutoff] = np.inf entireMask = (err==np.inf) maFrame = np.ma.masked_array(frame,entireMask) ''' apertureMask = aperture(guessX,guessY,radius=7) #if iFrame < 19: # err = np.ones(np.shape(frame))*10.0 #else: # err = np.zeros(np.shape(frame)) err = np.ones(np.shape(frame))*10.0 #err = (frame)**(0.5) err[apertureMask==1] = np.inf #weight points closer to the expected psf higher #err[frame>100] = np.inf frame[nanMask]=0#set to finite value that will be ignored err[nanMask] = np.inf#ignore these data points nearDeadCutoff=1#100/15 cps for 4000-6000 angstroms err[frame<nearDeadCutoff] = np.inf entireMask = (err==np.inf) maFrame = np.ma.masked_array(frame,entireMask) #try to make smart guesses about initial parameters #guessAmp = np.max(frame[frame!=np.nan]) #guessHeight = np.median(frame) #guessWidth = 1.5 guessAmp = 30. guessHeight = 5. guessWidth = 1.3 guessParams = [guessHeight,guessAmp,guessX,guessY,guessWidth] limitedmin = 5*[True] limitedmax = 5*[True] minpars = [0,0,0,0,0.1] #default min pars, usually work fine #minpars = [0,0,27,27,1] #tighter constraint on PSF width to avoid fitting wrong peak if PSF is divided by dead pixels maxpars = [40,200,43,43,10] #maxpars = [40,200,33,33,10] ''' #forced parameters for Landolt standard if iFrame == 27: minpars = [8,5,0,0,0.5] maxpars = [30,25,43,45,1.1] if iFrame == 28: minpars = [8,5,0,0,0.5] maxpars = [30,25,43,45,1.1] if iFrame == 29: minpars = [8,5,0,0,0.5] maxpars = [30,25,43,45,1.1] if iFrame == 30: minpars = [8,5,0,0,0.5] maxpars = [30,25,43,45,1.10] ''' usemoments=[True,True,True,True,True] #doesn't use our guess values, default #usemoments=[False,False,False,False,False] print "==========================" print wvls[iFrame] print "frame ",iFrame out = gaussfit(data=maFrame,err=err,params=guessParams,returnfitimage=True,quiet=True,limitedmin=limitedmin,limitedmax=limitedmax,minpars=minpars,maxpars=maxpars,circle=1,usemoments=usemoments,returnmp=True) mp = out[0] outparams = mp.params paramErrors = mp.perror chisq = mp.fnorm dof = mp.dof reducedChisq = chisq/dof print "reducedChisq =", reducedChisq fitimg = out[1] chisqList.append([chisq,dof]) paramsList.append(outparams) errorsList.append(paramErrors) print "outparams = ", outparams print "paramErrors = ", paramErrors # expectedResiduals = np.ma.masked_array(np.sqrt(frame),mask=entireMask) # residuals = np.ma.masked_array(np.abs(frame-fitimg),mask=entireMask) # utils.plotArray(expectedResiduals,cbar=True) # utils.plotArray(residuals,cbar=True) # fig = plt.figure() # ax = fig.add_subplot(111,projection='3d') # x = np.arange(0,44) # y = np.arange(0,46) # X,Y = np.meshgrid(x,y) # linearMask = np.ravel(entireMask==0) # ax.plot_wireframe(X,Y,fitimg) # ax.scatter(outparams[2],outparams[3],outparams[0]+outparams[1],c='black') # ax.scatter(np.ravel(X)[linearMask],np.ravel(Y)[linearMask],np.ravel(frame)[linearMask],c='red') # fitimg[nanMask]=0 # print fitimg[np.isnan(fitimg)] fitImgList.append(fitimg) # utils.plotArray(frame,cbar=True) # utils.plotArray(maFrame,cbar=True) # utils.plotArray(fitimg,cbar=True) # plt.show() # utils.confirm('Enter to continue.') # plt.close() # plt.close() # plt.close() frame[nanMask]=np.nan # fig = plt.figure() # ax1=fig.add_subplot(211) # ax2 = fig.add_subplot(212) # for iRow in range(len(frame)): # ax1.scatter(range(44),frame[iRow,:],c='red',marker='o',alpha=.5,label='data') # ax1.scatter(range(44),fitimg[iRow,:],c='blue',marker='^',alpha=.5,label='fit') # ax1.set_title('Fit seen along Cols') # for iCol in range(np.shape(frame)[1]): # ax2.scatter(range(46),frame[:,iCol],c='red',marker='o',alpha=.5,label='data') # ax2.scatter(range(46),fitimg[:,iCol],c='blue',marker='^',alpha=.5,label='fit') # ax2.set_title('Fit seen along Rows') # plt.show() plt.close() print 'closed' cube = np.array(fitImgList) chisqs = np.array(chisqList) params = np.array(paramsList) errors = np.array(errorsList) np.savez(npzfitpsf,fitImg=cube,params=params,errors=errors,chisqs=chisqs,wvls=wvls) print 'saved' utils.makeMovie(fitImgList,frameTitles=wvls, cbar=True, outName=giffitpsf, normMin=0, normMax=50)
bmazin/ARCONS-pipeline
examples/Pal2012_landoltPhot/fitPsf.py
Python
gpl-2.0
8,372
"use strict"; var log = require( "../class.log" ); var realmConfig = require( "../../config.realm" ).config; var quest = require( "../class.quest" ); exports.script = function( npcObject ) { // // Variables // var _iO = npcObject.getArgs().createdByInstanceObject, _cooldownPointer = null; var questIdConstant_62 = 49; var questParameterNameConstant_63 = "q49_3AttackFirstTargetDummy"; var numberConstant_64 = 1; // // Events override // npcObject.events._add( "damageTake", function( args ) { var fromCharacterObject_23 = args.fromCharacterObject; var amount_24 = args.amount; quest.questConditionUpdate( { characterObject: fromCharacterObject_23, questId: questIdConstant_62, parameterName: questParameterNameConstant_63, value: numberConstant_64, } ); }); // // Post all objects initialisation // this.postInit = function() { } // // Initialize // // bind to instance npcObject.events._add( "afterInit", function( args ) { npcObject.bindToInstance( _iO, function() { } ); }); }
victoralex/gameleon
includes/classes/class.npc.js_files/npcScript.221.js
JavaScript
gpl-2.0
1,247
#define BUF_SIZE 4096 #include <stdio.h> main(int argc, char *argv[]) { if(argc>1) { fprintf(stderr,"< entrada > salida\n"); return 1; } fprintf(stderr,"%s: running\n",argv[0]); for(;;) { double x[BUF_SIZE]; char y[BUF_SIZE]; int r = fread(x,sizeof(double),BUF_SIZE,stdin); if(r==0) break; { int i; for(i=0; i<r; i++) { if(x[i]<-128.0) y[i] = -128; else if(x[i]>127.0) y[i] = 127; else y[i]=(char)x[i]; } } fwrite(y,sizeof(char),r,stdout); } fprintf(stderr,"%s: done\n",argv[0]); }
vicente-gonzalez-ruiz/type-tools
double2char.c
C
gpl-2.0
554
<?php //custom post type portfolio if(! function_exists( 'kilobyte_custom_post_type_portfolio' )): function kilobyte_custom_post_type_portfolio(){ $labels = array( 'name'=>'Portfolio', 'singular_name'=>'Portfolio', 'add_new' => 'Add Portfolio', 'all_items' => 'All Portfolio', 'add_new_item'=> 'Add Portfolio', 'new_item' => 'New Portfolio', 'view_item' => 'View Portfolio', 'search_item' => 'Search Portfolio', 'not_found' => 'no items found', 'not_found_in_trash' => 'not found in trash', 'parent_item_colon' => 'parent' ); $args = array( 'labels' => $labels, 'public' => true, 'has_archive' => true, 'publicaly_queryable' => true, 'query_var' => true, 'rewrite' => true, 'capability_type' =>'post', 'heirarchical' => false, 'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'revisons', 'custom-fields', ), 'menu_position' => 5, 'rewrite' => array( 'slug' => 'portfolio','with_front' => false ), 'exclude_from_search' => false ); register_post_type('post-type-portfolio',$args); } endif; add_action('init','kilobyte_custom_post_type_portfolio' ); //custom post type Case Study if(!function_exists( 'kilobyte_custom_post_type_casestudy')): function kilobyte_custom_post_type_casestudy(){ $labels2 = array( 'name'=>'Case Study', 'singular_name'=>'Case Study', 'add_new' => 'Add Case Study', 'all_items' => 'All Case Study', 'add_new_item'=> 'Add Case Study', 'new_item' => 'New Case Study', 'view_item' => 'View Case Study', 'search_item' => 'Search Case Study', 'not_found' => 'no items found', 'not_found_in_trash' => 'not found in trash', 'parent_item_colon' => 'parent' ); $args2 = array( 'labels' => $labels2, 'public' => true, 'has_archive' => true, 'publicaly_queryable' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'casestudy','with_front' => false ), 'capability_type' =>'post', 'heirarchical' => false, 'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'revisons', 'post_formats', 'custom-fields' ), 'menu_position' => 6, 'exclude_from_search' => false ); register_post_type('post-type-casestudy',$args2); } endif; add_action('init','kilobyte_custom_post_type_casestudy' ); //custom taxonomies if ( ! function_exists( 'kilobyte_custom_taxonomy')): function kilobyte_custom_taxonomy(){ $labels = array( 'name' => 'Portfolio types', 'singular_name' => 'Portfolio types', 'search_items' => 'search types', 'all_items' => 'all types', 'parent_item' => 'parent Type', 'parent_item_colon' => 'parent Type', 'edit_item' => 'edit Type', 'update_item' => 'update Type', 'new_item_name' => 'new type Name', 'menu_name' => 'Portfolio types' ); $args = array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'portfolio/type','with_front' => false ), ); register_taxonomy('Portfolio Types',array('post-type-portfolio'),$args ); } endif; add_action('init','kilobyte_custom_taxonomy' ); // taxonomy for casestudy if ( ! function_exists( 'kilobyte_custom_taxonomy_casestudy')): function kilobyte_custom_taxonomy_casestudy(){ $labels = array( 'name' => 'Casestudy type', 'singular_name' => 'Casestudy type', 'search_items' => 'search types', 'all_items' => 'all types', 'parent_item' => 'parent Type', 'parent_item_colon' => 'parent Type', 'edit_item' => 'edit Type', 'update_item' => 'update Type', 'new_item_name' => 'new type Name', 'menu_name' => 'Casestudy type' ); $args = array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'casestudy/type' ), ); register_taxonomy('Casestudy type',array('post-type-casestudy'),$args ); } endif; add_action('init','kilobyte_custom_taxonomy_casestudy' ); //custom post type Personal blogs if(!function_exists( 'kilobyte_custom_post_type_Personalblogs')): function kilobyte_custom_post_type_Personalblogs(){ $labels = array( 'name'=>'Personal blogs', 'singular_name'=>'Personal blogs', 'add_new' => 'Add Personal blogs', 'all_items' => 'All Personal blogs', 'add_new_item'=> 'Add Personal blogs', 'new_item' => 'New Personal blogs', 'view_item' => 'View Personal blogs', 'search_item' => 'Search Personal blogs', 'not_found' => 'no items found', 'not_found_in_trash' => 'not found in trash', 'parent_item_colon' => 'parent' ); $args = array( 'labels' => $labels, 'public' => true, 'has_archive' => true, 'publicaly_queryable' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'Personalblogs','with_front' => false ), 'capability_type' =>'post', 'heirarchical' => false, 'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'revisons', 'post_formats', 'custom-fields' ), 'menu_position' => 7, 'exclude_from_search' => false ); register_post_type('Personalblogs',$args); } endif; add_action('init','kilobyte_custom_post_type_Personalblogs' ); // taxonomy for Personalblogs if ( ! function_exists( 'kilobyte_custom_taxonomy_Personalblogs')): function kilobyte_custom_taxonomy_Personalblogs(){ $labels = array( 'name' => 'Personalblogs type', 'singular_name' => 'Personalblogs type', 'search_items' => 'search types', 'all_items' => 'all types', 'parent_item' => 'parent Type', 'parent_item_colon' => 'parent Type', 'edit_item' => 'edit Type', 'update_item' => 'update Type', 'new_item_name' => 'new type Name', 'menu_name' => 'Personalblogs type' ); $args = array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'Personalblogs' ), ); register_taxonomy('Personalblogs type',array('post-type-Personalblogs'),$args ); } endif; add_action('init','kilobyte_custom_taxonomy_Personalblogs' );
shubham9411/kilobyte
inc/custom-posttype.php
PHP
gpl-2.0
6,356
/////////////////////////////////////////////////////////////////////////////// // // OpenFTA - Fault Tree Analysis // Copyright (C) 2005 FSC Limited // // 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 // // To contact FSC, please send an email to support@fsc.co.uk or write to // FSC Ltd., Cardiff Business Technology Centre, Senghenydd Road, Cardiff, // CF24 4AY. // /////////////////////////////////////////////////////////////////////////////// /*************************************************************** Module : File Utilities Author : FSC Limited Date : 5/8/96 SccsId : @(#)FileUtilities.c 1.3 12/16/96 Origin : FTA project, FSC Limited Private Venture, Level 2 Prototype. This module provides general purpose file handling routines. ***************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef WIN32 #include <unistd.h> #else #include <Io.h> #endif /* WIN32 */ #include <sys/stat.h> #include "FileUtilities.h" #include "StringUtilities.h" #include "util.h" #include "MemoryUtil.h" #include "AssertUtil.h" ASSERTFILE(__FILE__) #define FILE_EXISTS 0 /*--------------------------------------------------------------- Routine : generate_filename Purpose : Take file name (possibly with suffix) and generate name with different suffix e.g. generate_filename("thing.x", ".uvw") -> "thing.uvw" Returns pointer to heap. This routine will work if the filename is not simple as long as the pathname does not contain any '.' ---------------------------------------------------------------*/ char * generate_filename( char *fname, /* in: Filename string */ char *suffix ) /* in: Suffix string e.g., "*", "*.tla", ".tla" */ /* return: filename.suffix string */ { char *s = NULL; char *dot = strrchr(fname, '.'); int len_dot = (dot == NULL) ? 0 : strlen(dot); int curr_len_dot = 0; int len_fname = (fname == NULL) ? 0 : strlen(fname); /* int len_suffix = (suffix == NULL) ? 0 : strlen(suffix); */ /* int n = len_fname - len_dot; */ /* int len = n + len_suffix; */ ASSERT( fname != NULL); /* ASSERT( SU_Number_Of_Char( '.', fname, FALSE ) <= 1 ); */ /* if ( len_dot == 0 ) { */ /* if ( fNewMemory( (void *)&s, len_fname + 1 + len_suffix + 1 ) ) */ /* { */ /* strcpy( s, fname ); */ /* strcpy( s + len_fname, "." ); */ /* strcpy( s + len_fname + 1, suffix ); */ /* } */ /* else */ /* return NULL; */ /* } else { */ /* */ /* if ( n > 0 ) { */ /* if ( */ /* fNewMemory( */ /* (void *)&s, */ /* ( len_fname - len_dot + 1 ) + len_suffix + 1 ) ) */ /* { */ /* strcpy( s, fname ); */ /* strcpy( s + ( len_fname - len_dot + 1 ), suffix ); */ /* } */ /* else */ /* return NULL; */ /* } */ /* } */ /* return s; */ /* Alternatively... */ /* find position of LAST '.' in filename */ len_dot = 0; curr_len_dot = 0; do { curr_len_dot = SU_Location_Of( '.', &(fname[len_dot]), FALSE, TRUE ); len_dot += curr_len_dot + 1; curr_len_dot++; } while(curr_len_dot != 0 && (len_dot + curr_len_dot) < len_fname); len_dot--; if ( len_dot == 0 ) len_fname = (int)strlen( fname ); else len_fname = len_dot; if ( fNewMemory( (void **)&s, ( len_fname + 1 + (int)strlen( suffix ) + 1 ) ) ) { strcpy( s, fname ); strcpy( s + len_fname, "." ); strcpy( s + len_fname + 1, suffix ); return s; } else { return strsave( NULL ); } } /* generate_filename */ /*--------------------------------------------------------------- Routine : filename_from_pathname Purpose : Strips the filename from the end of the pathname supplied and returns a pointer to the filename. returns a pointer to the Heap. find last '/' if there is a last '/' then if last '/' not at end of pathname then allocate memory for string after last '/' copy pathname + position of '/' + 1 to new string return new string else return NULL end if; else return strsave( pathname ); end if; ---------------------------------------------------------------*/ char *filename_from_pathname(char *pathname ) { char *s = NULL; /* slash points to the last occurance of '/' with the pathname, so cannot be freed by this routine */ char *slash; /* int pos_slash; */ if ( pathname == NULL ) return NULL; #ifdef WIN32 if ( SU_Number_Of_Char( '\\', pathname, FALSE ) == 0 ) #else if ( SU_Number_Of_Char( '/', pathname, FALSE ) == 0 ) #endif { return strsave( pathname ); } else { #ifdef WIN32 slash = strrchr( pathname, '\\' ); #else slash = strrchr( pathname, '/' ); #endif if ( fNewMemory( (void **)&s, strlen( slash ) ) ) { strcpy( s, slash + 1 ); return s; } } return strsave( NULL ); } /* filename_from_pathname */ /*--------------------------------------------------------------- Routine : path_from_pathname Purpose : Strips the path from the start of the pathname supplied and returns a pointer to the path. returns a pointer to the Heap. find last '/' if there is a last '/' then if last '/' not at end of pathname then allocate memory for before last '/' copy pathname from 0 to position of '/' to new string return new string else return NULL end if; else return strsave( "" ); end if; ---------------------------------------------------------------*/ char *path_from_pathname(char *pathname ) { char *s = NULL; /* slash points to the last occurance of '/' with the pathname, so cannot be freed by this routine */ char *slash; /* int pos_slash; */ if ( pathname == NULL ) return NULL; #ifdef WIN32 if ( SU_Number_Of_Char( '\\', pathname, FALSE ) == 0 ) #else if ( SU_Number_Of_Char( '/', pathname, FALSE ) == 0 ) #endif { return strsave( NULL ); } else { #ifdef WIN32 slash = strrchr( pathname, '\\' ); #else slash = strrchr( pathname, '/' ); #endif if ( fNewMemory( (void **)&s, strlen(pathname) - strlen(slash+1) + 1) ) { /* copy relevant part of string and terminate with NULL char */ strncpy(s, pathname, strlen(pathname) - strlen(slash+1)); s[strlen(pathname) - strlen(slash+1)] = '\0'; return s; } } return strsave( NULL ); } /* path_from_pathname */ /*--------------------------------------------------------------- Routine : file_copy Purpose : Copies the file in from to the file in to. If the copy fails it returns non-zero ---------------------------------------------------------------*/ int file_copy( char *from, char *to ) { #ifdef WIN32 char *cmd = (char *)strsave( "copy \"" ); #else char *cmd = (char *)strsave( "cp \"" ); #endif int i; ASSERT( ( from != NULL ) && ( to != NULL ) ); cmd = (char *)strgrow( cmd, from ); cmd = (char *)strgrow( cmd, "\" \"" ); cmd = (char *)strgrow( cmd, to ); cmd = (char *)strgrow( cmd, "\"" ); i = system( cmd ); strfree( cmd ); return i; } /* file_copy */ /*--------------------------------------------------------------- Routine : date_of Purpose : Return date stamp of a file ---------------------------------------------------------------*/ time_t date_of( char *filename ) { struct stat stat_info; time_t date; ASSERT( filename != NULL ); /* check if file exists and get date stamp */ if ( stat(filename, &stat_info) == -1 ) { /* printf("date_of: file %s not found\n", filename); */ return 0; } else { date = stat_info.st_mtime; /* printf("date_of: %20s : %s", filename, ctime( &date )); */ } return date; } /* date_of */ /*--------------------------------------------------------------- Routine : file_exists Purpose : Return indication that a file exists ---------------------------------------------------------------*/ BOOL file_exists( char *filename ) { return file_is_valid( filename, F_OK ); } /* file_exists */ /*--------------------------------------------------------------- Routine : file_is_valid Purpose : Returns an indication of whether the file supplied can be accessed for the mode supplied. if (mode is read and file exists for read) or (mode is write and file does not exist) or (mode is write and file exists for write) or (mode is exists and file exists) then return True; else return False; end if; ---------------------------------------------------------------*/ BOOL file_is_valid( char *filename, int mode ) { char *s; /* ASSERT( filename != NULL ); */ if ( ( ( s = filename_from_pathname( filename ) ) != NULL ) && ( ( mode == R_OK ) && ( access( filename, mode ) == FILE_EXISTS ) ) || ( ( mode == W_OK ) && !( access( filename, F_OK ) == FILE_EXISTS ) ) || ( ( mode == W_OK ) && ( access( filename, mode ) == FILE_EXISTS ) ) || ( ( mode == F_OK ) && ( access( filename, mode ) == FILE_EXISTS ) ) ) { FreeMemory( s ); return TRUE; } else { FreeMemory( s ); return FALSE; } } /* file_is_valid */ /*--------------------------------------------------------------- Routine : file_has_suffix Purpose : Returns the suffix of the given filename, or NULL if no suffix exists. if filename has a dot then return characters after dot else return NULL; end if; ---------------------------------------------------------------*/ char * file_has_suffix( char *filename ) { char *dot_and_suffix = strrchr( filename, '.' ); int len_suffix = ( dot_and_suffix == NULL ) ? 0 : strlen( dot_and_suffix ) - 1; ASSERT( filename != NULL ); if ( len_suffix > 0 ) { return dot_and_suffix + 1; } return NULL; } /* file_has_suffix */ /*--------------------------------------------------------------- Routine : number_of_folders Purpose : returns the number of folders contained in a path ---------------------------------------------------------------*/ int num_folders_in_pathname( char *path ) { int num_chars; #ifdef WIN32 num_chars = SU_Number_Of_Char( '\\', path, FALSE ); #else num_chars = SU_Number_Of_Char( '/', path, FALSE ); #endif return num_chars; } /*--------------------------------------------------------------- Routine : file_separator Purpose : returns the value of the platform specific file separator ---------------------------------------------------------------*/ extern char file_separator() { #ifdef WIN32 return '\\'; #else return '/'; #endif }
jandcmoore/OpenFTA
src/lib/Utilities/FileUtilities.c
C
gpl-2.0
11,242
/* Copyright (C) 2009 Rob van Nieuwpoort & John Romein Astron P.O.Box 2, 7990 AA Dwingeloo, The Netherlands, nieuwpoort@astron.nl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef _CORRELATOR_1x1_H_ #define _CORRELATOR_1x1_H_ const CALchar* Kernel_1x1 = "il_ps_2_0\n" "dcl_input_position_interp(linear_noperspective) vWinCoord0.xy__\n" // position in domain (output buffer) "dcl_output_generic o0\n" "dcl_output_generic o1\n" "dcl_resource_id(0)_type(2d,unnorm)_fmtx(float)_fmty(float)_fmtz(float)_fmtw(float)\n" // samples "dcl_resource_id(1)_type(1d,unnorm)_fmtx(float)_fmty(float)_fmtz(float)_fmtw(float)\n" // cellToStatX "dcl_resource_id(2)_type(1d,unnorm)_fmtx(float)_fmty(float)_fmtz(float)_fmtw(float)\n" // cellToStatY "dcl_literal l0, 0x00000000, 0x00000000, 0x00000000, 0x00000000\n" "dcl_literal l1, 1.0, 2.0, 3.0, 4.0\n" "dcl_cb cb0[1]\n" // o0 -- o7 are the computed visibilities "mov o0, l0\n" // reals01 "mov o1, l0\n" // imags01 "mov r8.x, vWinCoord0.x\n" // r8.x = cell "mov r8.y00, vWinCoord0.y\n" // r8.y = channel "mov r9.x, cb0[0].x\n" // r9.x = nrStations (float) "mov r9.y, cb0[0].y\n" // r9.y = nrTimes (float) "mov r9.zw, l0\n" // r9.z = time loopcounter (0 .. nrTimes) "sample_resource(1)_sampler(0) r8.z, r8.x\n" // r8.z = stat0 (X) "sample_resource(2)_sampler(1) r8.w, r8.x\n" // r8.w = stat1 (Y) // indices should be (channel * nrStations) + station, time, 0, 0 "mul r10.y, r8.y, r9.x\n" "add r10.y, r10.y, r8.z\n" "mov r10.xzw, l0\n" // r10 = index0: {time, (channel * nrStations) + station0, 0, 0} "mul r12.y, r8.y, r9.x\n" "add r12.y, r12.y, r8.w\n" "mov r12.xzw, l0\n" // r10 = index0: {time, (channel * nrStations) + station1, 0, 0} "whileloop\n" " ge r9.w, r9.z, r9.y\n" // r9.w = temp used for comparison " break_logicalnz r9.w\n" // update time index " mov r10.x, r9.z\n" " mov r12.x, r9.z\n" // load the four samples #if DO_LOADS " sample_resource(0)_sampler(0) r20, r10\n" // sample 0 " sample_resource(0)_sampler(2) r22, r12\n" // sample 2 #else " mov r20, r10\n" " mov r22, r12\n" #endif #if DO_COMPUTATION " mad o0, r20.xxzz, r22.xzxz, o0\n" // reals02 += sample0.xxzz * sample2.xzxz " mad o0, r20.yyww, r22.ywyw, o0\n" // reals02 += sample0.yyww * sample2.ywyw " mad o1, r20.yyww, r22.xzxz, o1\n" // imags02 += sample0.yyww * sample2.xzxz " mul r30, r20.xxzz, r22.ywyw\n" // imags02 -= sample0.xxzz * sample2.ywyw " sub o1, o1, r30\n" #else " mov o0, r20\n" " mov o1, r21\n" #endif // DO_COMPUTATION " add r9.z, r9.z, r9.1\n" // increase loop counter "endloop\n" "end\n"; #endif // _CORRELATOR_1x1_H_
bnikolic/xcorrelators-bench
cal-correlator/correlator-1x1.h
C
gpl-2.0
3,305
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest19157") public class BenchmarkTest19157 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String[] values = request.getParameterValues("foo"); String param; if (values.length != 0) param = request.getParameterValues("foo")[0]; else param = null; String bar = doSomething(param); try { javax.crypto.Cipher c = javax.crypto.Cipher.getInstance("RSA/ECB/PKCS1Padding", "SunJCE"); } catch (java.security.NoSuchAlgorithmException e) { System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.lang.String) Test Case"); throw new ServletException(e); } catch (java.security.NoSuchProviderException e) { System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.lang.String) Test Case"); throw new ServletException(e); } catch (javax.crypto.NoSuchPaddingException e) { System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.lang.String) Test Case"); throw new ServletException(e); } response.getWriter().println("Crypto Test javax.crypto.Cipher.getInstance(java.lang.String,java.lang.String) executed"); } // end doPost private static String doSomething(String param) throws ServletException, IOException { java.util.List<String> valuesList = new java.util.ArrayList<String>( ); valuesList.add("safe"); valuesList.add( param ); valuesList.add( "moresafe" ); valuesList.remove(0); // remove the 1st safe value String bar = valuesList.get(1); // get the last 'safe' value return bar; } }
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest19157.java
Java
gpl-2.0
3,011
<?php /** * @file * Hooks provided the Entity module. */ /** * @addtogroup hooks * @{ */ /** * Inform the base system and the Field API about one or more entity types. * * Inform the system about one or more entity types (i.e., object types that * can be loaded via entity_load() and, optionally, to which fields can be * attached). * * @return * An array whose keys are entity type names and whose values identify * properties of those types that the system needs to know about: * - label: The human-readable name of the type. * - entity class: The name of the entity class, defaults to * Drupal\Core\Entity\Entity. The entity class must implement EntityInterface. * - controller class: The name of the class that is used to load the objects. * The class has to implement the * Drupal\Core\Entity\EntityStorageControllerInterface interface. Leave blank * to use the Drupal\Core\Entity\DatabaseStorageController implementation. * - render controller class: The name of the class that is used to render * the entities. Deafaults to Drupal\Core\Entity\EntityRenderController. * - form controller class: An associative array where the keys are the names * of the different form operations (such as creation, editing or deletion) * and the values are the names of the controller classes. To facilitate * supporting the case where an entity form varies only slightly between * different operations, the name of the operation is passed also to the * constructor of the form controller class. This way, one class can be used * for multiple entity forms. * - list controller class: The name of the class that is used to provide * listings of the entity. The class must implement * Drupal\Core\Entity\EntityListControllerInterface. Defaults to * Drupal\Core\Entity\EntityListController. * - base table: (used by Drupal\Core\Entity\DatabaseStorageController) The * name of the entity type's base table. * - static cache: (used by Drupal\Core\Entity\DatabaseStorageController) * FALSE to disable static caching of entities during a page request. * Defaults to TRUE. * - field cache: (used by Field API loading and saving of field data) FALSE * to disable Field API's persistent cache of field data. Only recommended * if a higher level persistent cache is available for the entity type. * Defaults to TRUE. * - uri callback: A function taking an entity as argument and returning the * URI elements of the entity, e.g. 'path' and 'options'. The actual entity * URI can be constructed by passing these elements to url(). * - label callback: (optional) A function taking an entity and optional langcode * argument, and returning the label of the entity. If langcode is omitted, the * entity's default language is used. * * The entity label is the main string associated with an entity; for * example, the title of a node or the subject of a comment. If there is an * entity object property that defines the label, use the 'label' element * of the 'entity keys' return value component to provide this information * (see below). If more complex logic is needed to determine the label of * an entity, you can instead specify a callback function here, which will * be called to determine the entity label. See also the * Drupal\Core\Entity\Entity::label() method, which implements this logic. * - fieldable: Set to TRUE if you want your entity type to be fieldable. * - translation: An associative array of modules registered as field * translation handlers. Array keys are the module names, array values * can be any data structure the module uses to provide field translation. * Any empty value disallows the module to appear as a translation handler. * - entity keys: An array describing how the Field API can extract the * information it needs from the objects of the type. Elements: * - id: The name of the property that contains the primary id of the * entity. Every entity object passed to the Field API must have this * property and its value must be numeric. * - revision: The name of the property that contains the revision id of * the entity. The Field API assumes that all revision ids are unique * across all entities of a type. This entry can be omitted if the * entities of this type are not versionable. * - bundle: The name of the property that contains the bundle name for the * entity. The bundle name defines which set of fields are attached to * the entity (e.g. what nodes call "content type"). This entry can be * omitted if this entity type exposes a single bundle (all entities have * the same collection of fields). The name of this single bundle will be * the same as the entity type. * - label: The name of the property that contains the entity label. For * example, if the entity's label is located in $entity->subject, then * 'subject' should be specified here. If complex logic is required to * build the label, a 'label callback' should be defined instead (see * the 'label callback' section above for details). * - uuid (optional): The name of the property that contains the universally * unique identifier of the entity, which is used to distinctly identify * an entity across different systems. * - bundle keys: An array describing how the Field API can extract the * information it needs from the bundle objects for this type (e.g * $vocabulary objects for terms; not applicable for nodes). This entry can * be omitted if this type's bundles do not exist as standalone objects. * Elements: * - bundle: The name of the property that contains the name of the bundle * object. * - bundles: An array describing all bundles for this object type. Keys are * bundles machine names, as found in the objects' 'bundle' property * (defined in the 'entity keys' entry above). Elements: * - label: The human-readable name of the bundle. * - uri callback: Same as the 'uri callback' key documented above for the * entity type, but for the bundle only. When determining the URI of an * entity, if a 'uri callback' is defined for both the entity type and * the bundle, the one for the bundle is used. * - admin: An array of information that allows Field UI pages to attach * themselves to the existing administration pages for the bundle. * Elements: * - path: the path of the bundle's main administration page, as defined * in hook_menu(). If the path includes a placeholder for the bundle, * the 'bundle argument', 'bundle helper' and 'real path' keys below * are required. * - bundle argument: The position of the placeholder in 'path', if any. * - real path: The actual path (no placeholder) of the bundle's main * administration page. This will be used to generate links. * - access callback: As in hook_menu(). 'user_access' will be assumed if * no value is provided. * - access arguments: As in hook_menu(). * - view modes: An array describing the view modes for the entity type. View * modes let entities be displayed differently depending on the context. * For instance, a node can be displayed differently on its own page * ('full' mode), on the home page or taxonomy listings ('teaser' mode), or * in an RSS feed ('rss' mode). Modules taking part in the display of the * entity (notably the Field API) can adjust their behavior depending on * the requested view mode. An additional 'default' view mode is available * for all entity types. This view mode is not intended for actual entity * display, but holds default display settings. For each available view * mode, administrators can configure whether it should use its own set of * field display settings, or just replicate the settings of the 'default' * view mode, thus reducing the amount of display configurations to keep * track of. Keys of the array are view mode names. Each view mode is * described by an array with the following key/value pairs: * - label: The human-readable name of the view mode * - custom settings: A boolean specifying whether the view mode should by * default use its own custom field display settings. If FALSE, entities * displayed in this view mode will reuse the 'default' display settings * by default (e.g. right after the module exposing the view mode is * enabled), but administrators can later use the Field UI to apply custom * display settings specific to the view mode. * * @see entity_load() * @see entity_load_multiple() * @see hook_entity_info_alter() */ function hook_entity_info() { $return = array( 'node' => array( 'label' => t('Node'), 'entity class' => 'Drupal\node\Node', 'controller class' => 'Drupal\node\NodeStorageController', 'form controller class' => array( 'default' => 'Drupal\node\NodeFormController', ), 'base table' => 'node', 'revision table' => 'node_revision', 'uri callback' => 'node_uri', 'fieldable' => TRUE, 'translation' => array( 'locale' => TRUE, ), 'entity keys' => array( 'id' => 'nid', 'revision' => 'vid', 'bundle' => 'type', 'uuid' => 'uuid', ), 'bundle keys' => array( 'bundle' => 'type', ), 'bundles' => array(), 'view modes' => array( 'full' => array( 'label' => t('Full content'), 'custom settings' => FALSE, ), 'teaser' => array( 'label' => t('Teaser'), 'custom settings' => TRUE, ), 'rss' => array( 'label' => t('RSS'), 'custom settings' => FALSE, ), ), ), ); // Search integration is provided by node.module, so search-related // view modes for nodes are defined here and not in search.module. if (module_exists('search')) { $return['node']['view modes'] += array( 'search_index' => array( 'label' => t('Search index'), 'custom settings' => FALSE, ), 'search_result' => array( 'label' => t('Search result'), 'custom settings' => FALSE, ), ); } // Bundles must provide a human readable name so we can create help and error // messages, and the path to attach Field admin pages to. foreach (node_type_get_names() as $type => $name) { $return['node']['bundles'][$type] = array( 'label' => $name, 'admin' => array( 'path' => 'admin/structure/types/manage/%node_type', 'real path' => 'admin/structure/types/manage/' . $type, 'bundle argument' => 4, 'access arguments' => array('administer content types'), ), ); } return $return; } /** * Alter the entity info. * * Modules may implement this hook to alter the information that defines an * entity. All properties that are available in hook_entity_info() can be * altered here. * * @param $entity_info * The entity info array, keyed by entity name. * * @see hook_entity_info() */ function hook_entity_info_alter(&$entity_info) { // Set the controller class for nodes to an alternate implementation of the // Drupal\Core\Entity\EntityStorageControllerInterface interface. $entity_info['node']['controller class'] = 'Drupal\mymodule\MyCustomNodeStorageController'; } /** * Act on entities when loaded. * * This is a generic load hook called for all entity types loaded via the * entity API. * * @param array $entities * The entities keyed by entity ID. * @param string $entity_type * The type of entities being loaded (i.e. node, user, comment). */ function hook_entity_load($entities, $entity_type) { foreach ($entities as $entity) { $entity->foo = mymodule_add_something($entity); } } /** * Act on an entity before it is about to be created or updated. * * @param Drupal\Core\Entity\EntityInterface $entity * The entity object. */ function hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity) { $entity->changed = REQUEST_TIME; } /** * Act on entities when inserted. * * @param Drupal\Core\Entity\EntityInterface $entity * The entity object. */ function hook_entity_insert(Drupal\Core\Entity\EntityInterface $entity) { // Insert the new entity into a fictional table of all entities. db_insert('example_entity') ->fields(array( 'type' => $entity->entityType(), 'id' => $entity->id(), 'created' => REQUEST_TIME, 'updated' => REQUEST_TIME, )) ->execute(); } /** * Act on entities when updated. * * @param Drupal\Core\Entity\EntityInterface $entity * The entity object. */ function hook_entity_update(Drupal\Core\Entity\EntityInterface $entity) { // Update the entity's entry in a fictional table of all entities. db_update('example_entity') ->fields(array( 'updated' => REQUEST_TIME, )) ->condition('type', $entity->entityType()) ->condition('id', $entity->id()) ->execute(); } /** * Act before entity deletion. * * This hook runs after the entity type-specific predelete hook. * * @param Drupal\Core\Entity\EntityInterface $entity * The entity object for the entity that is about to be deleted. */ function hook_entity_predelete(Drupal\Core\Entity\EntityInterface $entity) { // Count references to this entity in a custom table before they are removed // upon entity deletion. $id = $entity->id(); $type = $entity->entityType(); $count = db_select('example_entity_data') ->condition('type', $type) ->condition('id', $id) ->countQuery() ->execute() ->fetchField(); // Log the count in a table that records this statistic for deleted entities. $ref_count_record = (object) array( 'count' => $count, 'type' => $type, 'id' => $id, ); drupal_write_record('example_deleted_entity_statistics', $ref_count_record); } /** * Respond to entity deletion. * * This hook runs after the entity type-specific delete hook. * * @param Drupal\Core\Entity\EntityInterface $entity * The entity object for the entity that has been deleted. */ function hook_entity_delete(Drupal\Core\Entity\EntityInterface $entity) { // Delete the entity's entry from a fictional table of all entities. db_delete('example_entity') ->condition('type', $entity->entityType()) ->condition('id', $entity->id()) ->execute(); } /** * Alter or execute an Drupal\Core\Entity\EntityFieldQuery. * * @param Drupal\Core\Entity\EntityFieldQuery $query * An EntityFieldQuery. One of the most important properties to be changed is * EntityFieldQuery::executeCallback. If this is set to an existing function, * this function will get the query as its single argument and its result * will be the returned as the result of EntityFieldQuery::execute(). This can * be used to change the behavior of EntityFieldQuery entirely. For example, * the default implementation can only deal with one field storage engine, but * it is possible to write a module that can query across field storage * engines. Also, the default implementation presumes entities are stored in * SQL, but the execute callback could instead query any other entity storage, * local or remote. * * Note the $query->altered attribute which is TRUE in case the query has * already been altered once. This happens with cloned queries. * If there is a pager, then such a cloned query will be executed to count * all elements. This query can be detected by checking for * ($query->pager && $query->count), allowing the driver to return 0 from * the count query and disable the pager. */ function hook_entity_query_alter(Drupal\Core\Entity\EntityFieldQuery $query) { $query->executeCallback = 'my_module_query_callback'; } /** * Act on entities being assembled before rendering. * * @param Drupal\Core\Entity\EntityInterface $entity * The entity object. * @param $view_mode * The view mode the entity is rendered in. * @param $langcode * The language code used for rendering. * * The module may add elements to $entity->content prior to rendering. The * structure of $entity->content is a renderable array as expected by * drupal_render(). * * @see hook_entity_view_alter() * @see hook_comment_view() * @see hook_node_view() * @see hook_user_view() */ function hook_entity_view(Drupal\Core\Entity\EntityInterface $entity, $view_mode, $langcode) { $entity->content['my_additional_field'] = array( '#markup' => $additional_field, '#weight' => 10, '#theme' => 'mymodule_my_additional_field', ); } /** * Alter the results of ENTITY_view(). * * This hook is called after the content has been assembled in a structured * array and may be used for doing processing which requires that the complete * entity content structure has been built. * * If a module wishes to act on the rendered HTML of the entity rather than the * structured content array, it may use this hook to add a #post_render * callback. Alternatively, it could also implement hook_preprocess_HOOK() for * the particular entity type template, if there is one (e.g., node.tpl.php). * See drupal_render() and theme() for details. * * @param $build * A renderable array representing the entity content. * @param Drupal\Core\Entity\EntityInterface $entity * The entity object being rendered. * * @see hook_entity_view() * @see hook_comment_view_alter() * @see hook_node_view_alter() * @see hook_taxonomy_term_view_alter() * @see hook_user_view_alter() */ function hook_entity_view_alter(&$build, Drupal\Core\Entity\EntityInterface $entity) { if ($build['#view_mode'] == 'full' && isset($build['an_additional_field'])) { // Change its weight. $build['an_additional_field']['#weight'] = -10; // Add a #post_render callback to act on the rendered HTML of the entity. $build['#post_render'][] = 'my_module_node_post_render'; } } /** * Act on entities as they are being prepared for view. * * Allows you to operate on multiple entities as they are being prepared for * view. Only use this if attaching the data during the entity loading phase * is not appropriate, for example when attaching other 'entity' style objects. * * @param array $entities * The entities keyed by entity ID. * @param string $entity_type * The type of entities being viewed (i.e. node, user, comment). */ function hook_entity_prepare_view($entities, $entity_type) { // Load a specific node into the user object for later theming. if (!empty($entities) && $entity_type == 'user') { $nodes = mymodule_get_user_nodes(array_keys($entities)); foreach ($entities as $uid => $entity) { $entity->user_node = $nodes[$uid]; } } } /** * Change the view mode of an entity that is being displayed. * * @param string $view_mode * The view_mode that is to be used to display the entity. * @param Drupal\Core\Entity\EntityInterface $entity * The entity that is being viewed. * @param array $context * Array with additional context information, currently only contains the * langcode the entity is viewed in. */ function hook_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) { // For nodes, change the view mode when it is teaser. if ($entity->entityType() == 'node' && $view_mode == 'teaser') { $view_mode = 'my_custom_view_mode'; } } /** * Define custom entity properties. * * @param string $entity_type * The entity type for which to define entity properties. * * @return array * An array of property information having the following optional entries: * - definitions: An array of property definitions to add all entities of this * type, keyed by property name. See * Drupal\Core\TypedData\TypedDataManager::create() for a list of supported * keys in property definitions. * - optional: An array of property definitions for optional properties keyed * by property name. Optional properties are properties that only exist for * certain bundles of the entity type. * - bundle map: An array keyed by bundle name containing the names of * optional properties that entities of this bundle have. * * @see Drupal\Core\TypedData\TypedDataManager::create() * @see hook_entity_field_info_alter() * @see Drupal\Core\Entity\StorageControllerInterface::getPropertyDefinitions() */ function hook_entity_field_info($entity_type) { if (mymodule_uses_entity_type($entity_type)) { $info = array(); $info['definitions']['mymodule_text'] = array( 'type' => 'string_item', 'list' => TRUE, 'label' => t('The text'), 'description' => t('A text property added by mymodule.'), 'computed' => TRUE, 'class' => '\Drupal\mymodule\EntityComputedText', ); if ($entity_type == 'node') { // Add a property only to entities of the 'article' bundle. $info['optional']['mymodule_text_more'] = array( 'type' => 'string_item', 'list' => TRUE, 'label' => t('More text'), 'computed' => TRUE, 'class' => '\Drupal\mymodule\EntityComputedMoreText', ); $info['bundle map']['article'][0] = 'mymodule_text_more'; } return $info; } } /** * Alter defined entity properties. * * @param array $info * The property info array as returned by hook_entity_field_info(). * @param string $entity_type * The entity type for which entity properties are defined. * * @see hook_entity_field_info() */ function hook_entity_field_info_alter(&$info, $entity_type) { if (!empty($info['definitions']['mymodule_text'])) { // Alter the mymodule_text property to use a custom class. $info['definitions']['mymodule_text']['class'] = '\Drupal\anothermodule\EntityComputedText'; } }
dusik/realejuventudfan
core/includes/entity.api.php
PHP
gpl-2.0
22,131
# nullfs ## description nullfs implements a FUSE handler for a flat null filesystem. flat in that the handler allows the creation, reading, and writing of files but not of directories. null in that bytes are never committed to the file system when writing to a file and bytes are never returned when reading from a file, accomplished by the handler always returning success for those operations. ## usage ### create a mount point ```bash mkdir /mnt/null ``` ### invoke nullfs on that mount point ```bash nullfs /mnt/null ``` ## development ### code analysis Use splint (formerly lclint) to statically analyze the code. ### code style There is only one true bracket style. Use `astyle --style=otbs` to maintain coding conventions.
LucaFilipozzi/nullfs
README.md
Markdown
gpl-2.0
745
/**************************************************************************** ** $Id: qt/main.cpp 3.3.8 edited Jan 11 14:37 $ ** ** Copyright (C) 1992-2007 Trolltech ASA. All rights reserved. ** ** This file is part of an example program for Qt. This example ** program may be used, distributed and modified without limitation. ** *****************************************************************************/ #include <qapplication.h> #include "tooltip.h" int main( int argc, char ** argv ) { QApplication a( argc, argv ); TellMe mw; mw.setCaption( "Qt Example - Dynamic Tool Tips" ); a.setMainWidget( &mw ); mw.show(); return a.exec(); }
epatel/qt-mac-free-3.3.8
examples/tooltip/main.cpp
C++
gpl-2.0
679
#!/usr/bin/env python #encoding: utf-8 # Martin Kersner, m.kersner@gmail.com # 2016/03/17 from __future__ import print_function import os import sys import glob,cv2 from PIL import Image as PILImage import numpy as np from utils import mat2png_hariharan,pascal_palette_invert def main(): input_path, output_path = process_arguments(sys.argv) if os.path.isdir(input_path) and os.path.isdir(output_path): # glob.blob 返回所有匹配的文件路径列表 mat_files = glob.glob(os.path.join(input_path, '*.mat')) convert_mat2png(mat_files, output_path) else: help('Input or output path does not exist!\n') def process_arguments(argv): num_args = len(argv) input_path = None output_path = None if num_args == 3: input_path = argv[1] output_path = argv[2] else: help() if not os.path.exists(output_path): os.makedirs(output_path) return input_path, output_path def convert_mat2png(mat_files, output_path): if not mat_files: help('Input directory does not contain any Matlab files!\n') l2c = pascal_palette_invert() for ind,mat in enumerate(mat_files): print(ind,mat) numpy_img = mat2png_hariharan(mat) color = np.zeros( numpy_img.shape + (3,)) for l in l2c.keys(): color[numpy_img == l,:] = l2c[l] pil_img = PILImage.fromarray(color.astype('uint8')) #pil_img = PILImage.fromarray(numpy_img).convert("RGB") #for y in range(numpy_img.shape[0]): # for x in range(numpy_img.shape[1]): # c = l2c[numpy_img[y,x]] # pil_img.putpixel((x,y),c) #pil_img = PILImage.fromarray(numpy_img) pil_img.save(os.path.join(output_path, modify_image_name(mat, 'png'))) # Extract name of image from given path, replace its extension with specified one # and return new name only, not path. def modify_image_name(path, ext): return os.path.basename(path).split('.')[0] + '.' + ext def help(msg=''): print(msg + 'Usage: python mat2png.py INPUT_PATH OUTPUT_PATH\n' 'INPUT_PATH denotes path containing Matlab files for conversion.\n' 'OUTPUT_PATH denotes path where converted Png files ar going to be saved.' , file=sys.stderr) exit() if __name__ == '__main__': main()
z01nl1o02/tests
voc/sbd_dataset/mat2png.py
Python
gpl-2.0
2,232
<?php /** * Part of Component Schedule files. * * @copyright Copyright (C) 2014 Asikart. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ // No direct access defined('_JEXEC') or die; include_once JPATH_LIBRARIES . '/windwalker/src/init.php'; JForm::addFieldPath(WINDWALKER_SOURCE . '/Form/Fields'); JFormHelper::loadFieldClass('Modal'); /** * Supports a modal picker. */ class JFormFieldTask_Modal extends JFormFieldModal { /** * The form field type. * * @var string * @since 1.6 */ protected $type = 'Task_Modal'; /** * List name. * * @var string */ protected $view_list = 'tasks'; /** * Item name. * * @var string */ protected $view_item = 'task'; /** * Extension name, eg: com_content. * * @var string */ protected $extension = 'com_schedule'; }
skylying/ihealth-schedule
administrator/components/com_schedule/model/field/task/modal.php
PHP
gpl-2.0
864
/* * linux/fs/fat/file.c * * Written 1992,1993 by Werner Almesberger * * regular file handling primitives for fat-based filesystems */ #include <linux/capability.h> #include <linux/module.h> #include <linux/compat.h> #include <linux/mount.h> #include <linux/time.h> #include <linux/buffer_head.h> #include <linux/writeback.h> #include <linux/backing-dev.h> #include <linux/blkdev.h> #include <linux/fsnotify.h> #include <linux/security.h> #include "fat.h" static ssize_t fat_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { if (__mnt_is_readonly(file->f_path.mnt)) return -EROFS; return do_sync_write(file, buf, count, ppos); } static int fat_ioctl_get_attributes(struct inode *inode, u32 __user *user_attr) { u32 attr; mutex_lock(&inode->i_mutex); attr = fat_make_attrs(inode); mutex_unlock(&inode->i_mutex); return put_user(attr, user_attr); } static int fat_ioctl_set_attributes(struct file *file, u32 __user *user_attr) { struct inode *inode = file->f_path.dentry->d_inode; struct msdos_sb_info *sbi = MSDOS_SB(inode->i_sb); int is_dir = S_ISDIR(inode->i_mode); u32 attr, oldattr; struct iattr ia; int err; err = get_user(attr, user_attr); if (err) goto out; mutex_lock(&inode->i_mutex); err = mnt_want_write(file->f_path.mnt); if (err) goto out_unlock_inode; /* * ATTR_VOLUME and ATTR_DIR cannot be changed; this also * prevents the user from turning us into a VFAT * longname entry. Also, we obviously can't set * any of the NTFS attributes in the high 24 bits. */ attr &= 0xff & ~(ATTR_VOLUME | ATTR_DIR); /* Merge in ATTR_VOLUME and ATTR_DIR */ attr |= (MSDOS_I(inode)->i_attrs & ATTR_VOLUME) | (is_dir ? ATTR_DIR : 0); oldattr = fat_make_attrs(inode); /* Equivalent to a chmod() */ ia.ia_valid = ATTR_MODE | ATTR_CTIME; ia.ia_ctime = current_fs_time(inode->i_sb); if (is_dir) ia.ia_mode = fat_make_mode(sbi, attr, S_IRWXUGO); else { ia.ia_mode = fat_make_mode(sbi, attr, S_IRUGO | S_IWUGO | (inode->i_mode & S_IXUGO)); } /* The root directory has no attributes */ if (inode->i_ino == MSDOS_ROOT_INO && attr != ATTR_DIR) { err = -EINVAL; goto out_drop_write; } if (sbi->options.sys_immutable && ((attr | oldattr) & ATTR_SYS) && !capable(CAP_LINUX_IMMUTABLE)) { err = -EPERM; goto out_drop_write; } /* * The security check is questionable... We single * out the RO attribute for checking by the security * module, just because it maps to a file mode. */ err = security_inode_setattr(file->f_path.dentry, &ia); if (err) goto out_drop_write; /* This MUST be done before doing anything irreversible... */ err = fat_setattr(file->f_path.dentry, &ia); if (err) goto out_drop_write; fsnotify_change(file->f_path.dentry, ia.ia_valid); if (sbi->options.sys_immutable) { if (attr & ATTR_SYS) inode->i_flags |= S_IMMUTABLE; else inode->i_flags &= ~S_IMMUTABLE; } fat_save_attrs(inode, attr); mark_inode_dirty(inode); out_drop_write: mnt_drop_write(file->f_path.mnt); out_unlock_inode: mutex_unlock(&inode->i_mutex); out: return err; } long fat_generic_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct inode *inode = filp->f_path.dentry->d_inode; u32 __user *user_attr = (u32 __user *)arg; switch (cmd) { case FAT_IOCTL_GET_ATTRIBUTES: return fat_ioctl_get_attributes(inode, user_attr); case FAT_IOCTL_SET_ATTRIBUTES: return fat_ioctl_set_attributes(filp, user_attr); default: return -ENOTTY; /* Inappropriate ioctl for device */ } } #ifdef CONFIG_COMPAT static long fat_generic_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { return fat_generic_ioctl(filp, cmd, (unsigned long)compat_ptr(arg)); } #endif static int fat_file_release(struct inode *inode, struct file *filp) { if ((filp->f_mode & FMODE_WRITE) && MSDOS_SB(inode->i_sb)->options.flush) { fat_flush_inodes(inode->i_sb, inode, NULL); congestion_wait(BLK_RW_ASYNC, HZ/10); } return 0; } int fat_file_fsync(struct file *filp, int datasync) { struct inode *inode = filp->f_mapping->host; int res, err; res = generic_file_fsync(filp, datasync); err = sync_mapping_buffers(MSDOS_SB(inode->i_sb)->fat_inode->i_mapping); return res ? res : err; } const struct file_operations fat_file_operations = { .llseek = generic_file_llseek, .read = do_sync_read, .write = fat_write, .aio_read = generic_file_aio_read, .aio_write = generic_file_aio_write, .mmap = generic_file_mmap, .release = fat_file_release, .unlocked_ioctl = fat_generic_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = fat_generic_compat_ioctl, #endif .fsync = fat_file_fsync, .splice_read = generic_file_splice_read, }; static int fat_cont_expand(struct inode *inode, loff_t size) { struct address_space *mapping = inode->i_mapping; loff_t start = inode->i_size, count = size - inode->i_size; int err; err = generic_cont_expand_simple(inode, size); if (err) goto out; inode->i_ctime = inode->i_mtime = CURRENT_TIME_SEC; mark_inode_dirty(inode); if (IS_SYNC(inode)) { int err2; /* * Opencode syncing since we don't have a file open to use * standard fsync path. */ err = filemap_fdatawrite_range(mapping, start, start + count - 1); err2 = sync_mapping_buffers(mapping); if (!err) err = err2; err2 = write_inode_now(inode, 1); if (!err) err = err2; if (!err) { err = filemap_fdatawait_range(mapping, start, start + count - 1); } } out: return err; } /* Free all clusters after the skip'th cluster. */ static int fat_free(struct inode *inode, int skip) { struct super_block *sb = inode->i_sb; int err, wait, free_start, i_start, i_logstart; if (MSDOS_I(inode)->i_start == 0) return 0; fat_cache_inval_inode(inode); wait = IS_DIRSYNC(inode); i_start = free_start = MSDOS_I(inode)->i_start; i_logstart = MSDOS_I(inode)->i_logstart; /* First, we write the new file size. */ if (!skip) { MSDOS_I(inode)->i_start = 0; MSDOS_I(inode)->i_logstart = 0; } MSDOS_I(inode)->i_attrs |= ATTR_ARCH; inode->i_ctime = inode->i_mtime = CURRENT_TIME_SEC; if (wait) { err = fat_sync_inode(inode); if (err) { MSDOS_I(inode)->i_start = i_start; MSDOS_I(inode)->i_logstart = i_logstart; return err; } } else mark_inode_dirty(inode); /* Write a new EOF, and get the remaining cluster chain for freeing. */ if (skip) { struct fat_entry fatent; int ret, fclus, dclus; ret = fat_get_cluster(inode, skip - 1, &fclus, &dclus); if (ret < 0) return ret; else if (ret == FAT_ENT_EOF) return 0; fatent_init(&fatent); ret = fat_ent_read(inode, &fatent, dclus); if (ret == FAT_ENT_EOF) { fatent_brelse(&fatent); return 0; } else if (ret == FAT_ENT_FREE) { fat_fs_error(sb, "%s: invalid cluster chain (i_pos %lld)", __func__, MSDOS_I(inode)->i_pos); ret = -EIO; } else if (ret > 0) { err = fat_ent_write(inode, &fatent, FAT_ENT_EOF, wait); if (err) ret = err; } fatent_brelse(&fatent); if (ret < 0) return ret; free_start = ret; } inode->i_blocks = skip << (MSDOS_SB(sb)->cluster_bits - 9); /* Freeing the remained cluster chain */ return fat_free_clusters(inode, free_start); } void fat_truncate_blocks(struct inode *inode, loff_t offset) { struct msdos_sb_info *sbi = MSDOS_SB(inode->i_sb); const unsigned int cluster_size = sbi->cluster_size; int nr_clusters; /* * This protects against truncating a file bigger than it was then * trying to write into the hole. */ if (MSDOS_I(inode)->mmu_private > offset) MSDOS_I(inode)->mmu_private = offset; nr_clusters = (offset + (cluster_size - 1)) >> sbi->cluster_bits; fat_free(inode, nr_clusters); fat_flush_inodes(inode->i_sb, inode, NULL); } int fat_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat) { struct inode *inode = dentry->d_inode; generic_fillattr(inode, stat); stat->blksize = MSDOS_SB(inode->i_sb)->cluster_size; return 0; } EXPORT_SYMBOL_GPL(fat_getattr); static int fat_sanitize_mode(const struct msdos_sb_info *sbi, struct inode *inode, umode_t *mode_ptr) { mode_t mask, perm; /* * Note, the basic check is already done by a caller of * (attr->ia_mode & ~FAT_VALID_MODE) */ if (S_ISREG(inode->i_mode)) mask = sbi->options.fs_fmask; else mask = sbi->options.fs_dmask; perm = *mode_ptr & ~(S_IFMT | mask); /* * Of the r and x bits, all (subject to umask) must be present. Of the * w bits, either all (subject to umask) or none must be present. * * If fat_mode_can_hold_ro(inode) is false, can't change w bits. */ if ((perm & (S_IRUGO | S_IXUGO)) != (inode->i_mode & (S_IRUGO|S_IXUGO))) return -EPERM; if (fat_mode_can_hold_ro(inode)) { if ((perm & S_IWUGO) && ((perm & S_IWUGO) != (S_IWUGO & ~mask))) return -EPERM; } else { if ((perm & S_IWUGO) != (S_IWUGO & ~mask)) return -EPERM; } *mode_ptr &= S_IFMT | perm; return 0; } static int fat_allow_set_time(struct msdos_sb_info *sbi, struct inode *inode) { mode_t allow_utime = sbi->options.allow_utime; if (current_fsuid() != inode->i_uid) { if (in_group_p(inode->i_gid)) allow_utime >>= 3; if (allow_utime & MAY_WRITE) return 1; } /* use a default check */ return 0; } #define TIMES_SET_FLAGS (ATTR_MTIME_SET | ATTR_ATIME_SET | ATTR_TIMES_SET) /* valid file mode bits */ #define FAT_VALID_MODE (S_IFREG | S_IFDIR | S_IRWXUGO) int fat_setattr(struct dentry *dentry, struct iattr *attr) { struct msdos_sb_info *sbi = MSDOS_SB(dentry->d_sb); struct inode *inode = dentry->d_inode; unsigned int ia_valid; int error; /* Check for setting the inode time. */ ia_valid = attr->ia_valid; if (ia_valid & TIMES_SET_FLAGS) { if (fat_allow_set_time(sbi, inode)) attr->ia_valid &= ~TIMES_SET_FLAGS; } error = inode_change_ok(inode, attr); attr->ia_valid = ia_valid; if (error) { if (sbi->options.quiet) error = 0; goto out; } /* * Expand the file. Since inode_setattr() updates ->i_size * before calling the ->truncate(), but FAT needs to fill the * hole before it. XXX: this is no longer true with new truncate * sequence. */ if (attr->ia_valid & ATTR_SIZE) { if (attr->ia_size > inode->i_size) { error = fat_cont_expand(inode, attr->ia_size); if (error || attr->ia_valid == ATTR_SIZE) goto out; attr->ia_valid &= ~ATTR_SIZE; } } if (((attr->ia_valid & ATTR_UID) && (attr->ia_uid != sbi->options.fs_uid)) || ((attr->ia_valid & ATTR_GID) && (attr->ia_gid != sbi->options.fs_gid)) || ((attr->ia_valid & ATTR_MODE) && (attr->ia_mode & ~FAT_VALID_MODE))) error = -EPERM; if (error) { if (sbi->options.quiet) error = 0; goto out; } /* * We don't return -EPERM here. Yes, strange, but this is too * old behavior. */ if (attr->ia_valid & ATTR_MODE) { if (fat_sanitize_mode(sbi, inode, &attr->ia_mode) < 0) attr->ia_valid &= ~ATTR_MODE; } if (attr->ia_valid & ATTR_SIZE) { truncate_setsize(inode, attr->ia_size); fat_truncate_blocks(inode, attr->ia_size); } setattr_copy(inode, attr); mark_inode_dirty(inode); out: return error; } EXPORT_SYMBOL_GPL(fat_setattr); const struct inode_operations fat_file_inode_operations = { .setattr = fat_setattr, .getattr = fat_getattr, };
acroreiser/kernel_samsung_msm
fs/fat/file.c
C
gpl-2.0
11,286
package zhangXiaoXiang.s02_; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author Bob * @ClassName: HelloServlet * @Description: servlet代码初探(本段注释来自《Servlet与JSP核心编程》,而不是张孝祥视频讲解) * @1 servlet是常规的java代码:这段代码用了新的API,但不涉及新的语法 * @2 servlet和JSP API不属于java2 平台标准版(Java 2 Platform,Standard Edition,J2SE);他们是单独的规范 * @3 它对标准的类(HttpServlet)进行了扩展:servlet为应对HTTP提供了大量的基础结构 * @4 它覆盖了doGet方法:servlet用不同的方法响应不同类型的HTTP命令 * @date 2015年2月13日 下午1:14:27 */ public class HelloServlet extends HttpServlet { private static final long serialVersionUID = -2264760525610612443L; /** * servlet */ public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { PrintWriter pw = response.getWriter(); pw.println("<html>"); pw.println("<font size = 30 color=red>Hello servlet !</font><br>"); pw.println("<marquee>" + new java.util.Date() + "</marquee>"); pw.println("</html>"); } }
NorthFacing/step-by-Java
web-servletAndJsp/src/main/java/zhangXiaoXiang/s02_/HelloServlet.java
Java
gpl-2.0
1,343
package com.vv.minerlamp.entity; import java.sql.Blob; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "staff") public class Staff { private Long id; private Long workId; private String name; private Integer sex; private String birthDate; private String certificateNo; private String eduLevel; private String phone; private String address; private Long rackId; private Long lampNo; private Long professionId; private String profession; private Long departmentId; private String department; private Long clazzId; private String clazz; private Blob image; private Date chargingLastTime; //ÃüÃûÓÐÎó£¬Êµ¼ÊÊÇ×¼±¸Ï¾®Ê±¼ä£¬¶ø²»ÊÇ¿ªÊ¼³äµçʱ¼ä // public static final int BATTERY_NOTUSE = 0; // public static final int BATTERY_UNDERGROUND = 1; // public static final int BATTERY_CHARGING = 2; // public static final int BATTERY_FULL = 3; // public static final int BATTERY_ERROR = 4; // // public static final int BATTERY_ACTION_NEW = 0; // public static final int BATTERY_ACTION_EDIT = 1; // public static final int BATTERY_ACTION_DELETE = 2; public static final int STAFF_MODEL_TYPE_1 = 1; public static final int STAFF_MODEL_TYPE_2 = 2; public Staff() { } public Staff(Long workId, String name, int sex, String birthDate, String certificateNo, String eduLevel, String phone, String address, Long rackId, Long lampNo, Long professionId, String profession, Long departmentId, String department, Long clazzId, String clazz, Blob image) { super(); this.workId = workId; this.name = name; this.sex = sex; this.birthDate = birthDate; this.certificateNo = certificateNo; this.eduLevel = eduLevel; this.phone = phone; this.address = address; this.rackId = rackId; this.lampNo = lampNo; this.professionId = professionId; this.profession = profession; this.departmentId = departmentId; this.department = department; this.clazzId = clazzId; this.clazz = clazz; this.image = image; } @Id @GeneratedValue @Column(name = "ID") public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(name = "name", nullable = false) public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(name = "work_id", nullable = false) public Long getWorkId() { return workId; } public void setWorkId(Long workId) { this.workId = workId; } @Column(name = "sex") public Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } @Column(name = "birth_date") public String getBirthDate() { return birthDate; } public void setBirthDate(String birthDate) { this.birthDate = birthDate; } @Column(name = "certificate_no") public String getCertificateNo() { return certificateNo; } public void setCertificateNo(String certificateNo) { this.certificateNo = certificateNo; } @Column(name = "edu_level") public String getEduLevel() { return eduLevel; } public void setEduLevel(String eduLevel) { this.eduLevel = eduLevel; } @Column(name = "phone") public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } @Column(name = "address") public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Column(name = "rack_id") public Long getRackId() { return rackId; } public void setRackId(Long rackId) { this.rackId = rackId; } @Column(name = "lamp_no") public Long getLampNo() { return lampNo; } public void setLampNo(Long lampNo) { this.lampNo = lampNo; } @Column(name = "profession_id") public Long getProfessionId() { return professionId; } public void setProfessionId(Long professionId) { this.professionId = professionId; } @Column(name = "profession") public String getProfession() { return profession; } public void setProfession(String profession) { this.profession = profession; } @Column(name = "department_id") public Long getDepartmentId() { return departmentId; } public void setDepartmentId(Long departmentId) { this.departmentId = departmentId; } @Column(name = "department") public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } @Column(name = "clazz_id") public Long getClazzId() { return clazzId; } public void setClazzId(Long clazzId) { this.clazzId = clazzId; } @Column(name = "clazz") public String getClazz() { return clazz; } public void setClazz(String clazz) { this.clazz = clazz; } @Column(name = "image") public Blob getImage() { return image; } public void setImage(Blob image) { this.image = image; } @Column(name = "charging_lasttime") public Date getChargingLastTime() { return chargingLastTime; } public void setChargingLastTime(Date chargingLastTime) { this.chargingLastTime = chargingLastTime; } @Override public String toString() { return name; } }
vvdeng/MinerLampSystem
src/com/vv/minerlamp/entity/Staff.java
Java
gpl-2.0
5,423
package moviescraper.doctord.controller.xmlserialization; import java.io.IOException; import moviescraper.doctord.model.dataitem.Thumb; /** * Helper class for serializing a fanart object to and from XML */ public class KodiXmlFanartBean { private String[] thumb; public KodiXmlFanartBean(String[] thumb) { super(); this.thumb = thumb; } public KodiXmlFanartBean(Thumb[] thumb) { if (thumb.length == 0) { this.thumb = new String[0]; } else { this.thumb = new String[thumb.length]; for (int i = 0; i < thumb.length; i++) { this.thumb[i] = thumb[i].getThumbURL().toString(); } } } public String[] getThumb() { return thumb; } public void setThumb(String[] thumb) { this.thumb = thumb; } public Thumb[] toFanart() throws IOException { Thumb[] fanart = new Thumb[thumb.length]; for (int i = 0; i < fanart.length; i++) { fanart[i] = new Thumb(thumb[i]); } return fanart; } }
DoctorD1501/JAVMovieScraper
src/main/java/moviescraper/doctord/controller/xmlserialization/KodiXmlFanartBean.java
Java
gpl-2.0
931
JqueryComingSoonPage ==================== Coming Soon Page with Contact Form and Mysql Database
OssamaElGartet/JqueryComingSoonPage
README.md
Markdown
gpl-2.0
97
/* Generic API to adapt to */ #include<linux/buffer_head.h> #include<linux/bio.h> #include <linux/err.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/kmod.h> #include <linux/module.h> #include <linux/param.h> #include <linux/sched/signal.h> #include <linux/slab.h> #include <linux/string.h> #include "internal.h" LIST_HEAD(crypto_alg_list); EXPORT_SYMBOL_GPL(crypto_alg_list); DECLARE_RWSEM(crypto_alg_sem); EXPORT_SYMBOL_GPL(crypto_alg_sem); BLOCKING_NOTIFIER_HEAD(crypto_chain); EXPORT_SYMBOL_GPL(crypto_chain); static struct crypto_alg *crypto_larval_wait(struct crypto_alg *alg); struct crypto_alg *crypto_mod_get(struct crypto_alg *alg) { return try_module_get(alg->cra_module) ? crypto_alg_get(alg) : NULL; } EXPORT_SYMBOL_GPL(crypto_mod_get); void crypto_mod_put(struct crypto_alg *alg) { struct module *module = alg->cra_module; crypto_alg_put(alg); module_put(module); } EXPORT_SYMBOL_GPL(crypto_mod_put); static inline int crypto_is_test_larval(struct crypto_larval *larval) { return larval->alg.cra_driver_name[0]; } static struct crypto_alg *__crypto_alg_lookup(const char *name, u32 type, u32 mask) { struct crypto_alg *q, *alg = NULL; int best = -2; list_for_each_entry(q, &crypto_alg_list, cra_list) { int exact, fuzzy; if (crypto_is_moribund(q)) continue; if ((q->cra_flags ^ type) & mask) continue; if (crypto_is_larval(q) && !crypto_is_test_larval((struct crypto_larval *)q) && ((struct crypto_larval *)q)->mask != mask) continue; exact = !strcmp(q->cra_driver_name, name); fuzzy = !strcmp(q->cra_name, name); if (!exact && !(fuzzy && q->cra_priority > best)) continue; if (unlikely(!crypto_mod_get(q))) continue; best = q->cra_priority; if (alg) crypto_mod_put(alg); alg = q; if (exact) break; } return alg; } static void crypto_larval_destroy(struct crypto_alg *alg) { struct crypto_larval *larval = (void *)alg; BUG_ON(!crypto_is_larval(alg)); if (larval->adult) crypto_mod_put(larval->adult); kfree(larval); } struct crypto_larval *crypto_larval_alloc(const char *name, u32 type, u32 mask) { struct crypto_larval *larval; larval = kzalloc(sizeof(*larval), GFP_KERNEL); if (!larval) return ERR_PTR(-ENOMEM); larval->mask = mask; larval->alg.cra_flags = CRYPTO_ALG_LARVAL | type; larval->alg.cra_priority = -1; larval->alg.cra_destroy = crypto_larval_destroy; strlcpy(larval->alg.cra_name, name, CRYPTO_MAX_ALG_NAME); init_completion(&larval->completion); return larval; } EXPORT_SYMBOL_GPL(crypto_larval_alloc); static struct crypto_alg *crypto_larval_add(const char *name, u32 type, u32 mask) { struct crypto_alg *alg; struct crypto_larval *larval; larval = crypto_larval_alloc(name, type, mask); if (IS_ERR(larval)) return ERR_CAST(larval); atomic_set(&larval->alg.cra_refcnt, 2); down_write(&crypto_alg_sem); alg = __crypto_alg_lookup(name, type, mask); if (!alg) { alg = &larval->alg; list_add(&alg->cra_list, &crypto_alg_list); } up_write(&crypto_alg_sem); if (alg != &larval->alg) { kfree(larval); if (crypto_is_larval(alg)) alg = crypto_larval_wait(alg); } return alg; } void crypto_larval_kill(struct crypto_alg *alg) { struct crypto_larval *larval = (void *)alg; down_write(&crypto_alg_sem); list_del(&alg->cra_list); up_write(&crypto_alg_sem); complete_all(&larval->completion); crypto_alg_put(alg); } EXPORT_SYMBOL_GPL(crypto_larval_kill); static struct crypto_alg *crypto_larval_wait(struct crypto_alg *alg) { struct crypto_larval *larval = (void *)alg; long timeout; timeout = wait_for_completion_killable_timeout( &larval->completion, 60 * HZ); alg = larval->adult; if (timeout < 0) alg = ERR_PTR(-EINTR); else if (!timeout) alg = ERR_PTR(-ETIMEDOUT); else if (!alg) alg = ERR_PTR(-ENOENT); else if (crypto_is_test_larval(larval) && !(alg->cra_flags & CRYPTO_ALG_TESTED)) alg = ERR_PTR(-EAGAIN); else if (!crypto_mod_get(alg)) alg = ERR_PTR(-EAGAIN); crypto_mod_put(&larval->alg); return alg; } struct crypto_alg *crypto_alg_lookup(const char *name, u32 type, u32 mask) { struct crypto_alg *alg; down_read(&crypto_alg_sem); alg = __crypto_alg_lookup(name, type, mask); up_read(&crypto_alg_sem); return alg; } EXPORT_SYMBOL_GPL(crypto_alg_lookup); struct crypto_alg *crypto_larval_lookup(const char *name, u32 type, u32 mask) { struct crypto_alg *alg; if (!name) return ERR_PTR(-ENOENT); type &= ~(CRYPTO_ALG_LARVAL | CRYPTO_ALG_DEAD); mask &= ~(CRYPTO_ALG_LARVAL | CRYPTO_ALG_DEAD); alg = crypto_alg_lookup(name, type, mask); if (!alg) { request_module("crypto-%s", name); if (!((type ^ CRYPTO_ALG_NEED_FALLBACK) & mask & CRYPTO_ALG_NEED_FALLBACK)) request_module("crypto-%s-all", name); alg = crypto_alg_lookup(name, type, mask); } if (alg) return crypto_is_larval(alg) ? crypto_larval_wait(alg) : alg; return crypto_larval_add(name, type, mask); } EXPORT_SYMBOL_GPL(crypto_larval_lookup); int crypto_probing_notify(unsigned long val, void *v) { int ok; ok = blocking_notifier_call_chain(&crypto_chain, val, v); if (ok == NOTIFY_DONE) { request_module("cryptomgr"); ok = blocking_notifier_call_chain(&crypto_chain, val, v); } return ok; } EXPORT_SYMBOL_GPL(crypto_probing_notify); struct crypto_alg *crypto_alg_mod_lookup(const char *name, u32 type, u32 mask) { struct crypto_alg *alg; struct crypto_alg *larval; int ok; if (!((type | mask) & CRYPTO_ALG_TESTED)) { type |= CRYPTO_ALG_TESTED; mask |= CRYPTO_ALG_TESTED; } /* * If the internal flag is set for a cipher, require a caller to * to invoke the cipher with the internal flag to use that cipher. * Also, if a caller wants to allocate a cipher that may or may * not be an internal cipher, use type | CRYPTO_ALG_INTERNAL and * !(mask & CRYPTO_ALG_INTERNAL). */ if (!((type | mask) & CRYPTO_ALG_INTERNAL)) mask |= CRYPTO_ALG_INTERNAL; larval = crypto_larval_lookup(name, type, mask); if (IS_ERR(larval) || !crypto_is_larval(larval)) return larval; ok = crypto_probing_notify(CRYPTO_MSG_ALG_REQUEST, larval); if (ok == NOTIFY_STOP) alg = crypto_larval_wait(larval); else { crypto_mod_put(larval); alg = ERR_PTR(-ENOENT); } crypto_larval_kill(larval); return alg; } EXPORT_SYMBOL_GPL(crypto_alg_mod_lookup); static int crypto_init_ops(struct crypto_tfm *tfm, u32 type, u32 mask) { const struct crypto_type *type_obj = tfm->__crt_alg->cra_type; if (type_obj) return type_obj->init(tfm, type, mask); switch (crypto_tfm_alg_type(tfm)) { case CRYPTO_ALG_TYPE_CIPHER: return crypto_init_cipher_ops(tfm); case CRYPTO_ALG_TYPE_COMPRESS: return crypto_init_compress_ops(tfm); default: break; } BUG(); return -EINVAL; } static void crypto_exit_ops(struct crypto_tfm *tfm) { const struct crypto_type *type = tfm->__crt_alg->cra_type; if (type && tfm->exit) tfm->exit(tfm); } static unsigned int crypto_ctxsize(struct crypto_alg *alg, u32 type, u32 mask) { const struct crypto_type *type_obj = alg->cra_type; unsigned int len; len = alg->cra_alignmask & ~(crypto_tfm_ctx_alignment() - 1); if (type_obj) return len + type_obj->ctxsize(alg, type, mask); switch (alg->cra_flags & CRYPTO_ALG_TYPE_MASK) { default: BUG(); case CRYPTO_ALG_TYPE_CIPHER: len += crypto_cipher_ctxsize(alg); break; case CRYPTO_ALG_TYPE_COMPRESS: len += crypto_compress_ctxsize(alg); break; } return len; } void crypto_shoot_alg(struct crypto_alg *alg) { down_write(&crypto_alg_sem); alg->cra_flags |= CRYPTO_ALG_DYING; up_write(&crypto_alg_sem); } EXPORT_SYMBOL_GPL(crypto_shoot_alg); struct crypto_tfm *__crypto_alloc_tfm(struct crypto_alg *alg, u32 type, u32 mask) { struct crypto_tfm *tfm = NULL; unsigned int tfm_size; int err = -ENOMEM; tfm_size = sizeof(*tfm) + crypto_ctxsize(alg, type, mask); tfm = kzalloc(tfm_size, GFP_KERNEL); if (tfm == NULL) goto out_err; tfm->__crt_alg = alg; err = crypto_init_ops(tfm, type, mask); if (err) goto out_free_tfm; if (!tfm->exit && alg->cra_init && (err = alg->cra_init(tfm))) goto cra_init_failed; goto out; cra_init_failed: crypto_exit_ops(tfm); out_free_tfm: if (err == -EAGAIN) crypto_shoot_alg(alg); kfree(tfm); out_err: tfm = ERR_PTR(err); out: return tfm; } EXPORT_SYMBOL_GPL(__crypto_alloc_tfm); /* * crypto_alloc_base - Locate algorithm and allocate transform * @alg_name: Name of algorithm * @type: Type of algorithm * @mask: Mask for type comparison * * This function should not be used by new algorithm types. * Please use crypto_alloc_tfm instead. * * crypto_alloc_base() will first attempt to locate an already loaded * algorithm. If that fails and the kernel supports dynamically loadable * modules, it will then attempt to load a module of the same name or * alias. If that fails it will send a query to any loaded crypto manager * to construct an algorithm on the fly. A refcount is grabbed on the * algorithm which is then associated with the new transform. * * The returned transform is of a non-determinate type. Most people * should use one of the more specific allocation functions such as * crypto_alloc_blkcipher. * * In case of error the return value is an error pointer. */ struct crypto_tfm *crypto_alloc_base(const char *alg_name, u32 type, u32 mask) { struct crypto_tfm *tfm; int err; for (;;) { struct crypto_alg *alg; alg = crypto_alg_mod_lookup(alg_name, type, mask); if (IS_ERR(alg)) { err = PTR_ERR(alg); goto err; } tfm = __crypto_alloc_tfm(alg, type, mask); if (!IS_ERR(tfm)) return tfm; crypto_mod_put(alg); err = PTR_ERR(tfm); err: if (err != -EAGAIN) break; if (fatal_signal_pending(current)) { err = -EINTR; break; } } return ERR_PTR(err); } EXPORT_SYMBOL_GPL(crypto_alloc_base); void *crypto_create_tfm(struct crypto_alg *alg, const struct crypto_type *frontend) { char *mem; struct crypto_tfm *tfm = NULL; unsigned int tfmsize; unsigned int total; int err = -ENOMEM; tfmsize = frontend->tfmsize; total = tfmsize + sizeof(*tfm) + frontend->extsize(alg); mem = kzalloc(total, GFP_KERNEL); if (mem == NULL) goto out_err; tfm = (struct crypto_tfm *)(mem + tfmsize); tfm->__crt_alg = alg; err = frontend->init_tfm(tfm); if (err) goto out_free_tfm; if (!tfm->exit && alg->cra_init && (err = alg->cra_init(tfm))) goto cra_init_failed; goto out; cra_init_failed: crypto_exit_ops(tfm); out_free_tfm: if (err == -EAGAIN) crypto_shoot_alg(alg); kfree(mem); out_err: mem = ERR_PTR(err); out: return mem; } EXPORT_SYMBOL_GPL(crypto_create_tfm); struct crypto_alg *crypto_find_alg(const char *alg_name, const struct crypto_type *frontend, u32 type, u32 mask) { struct crypto_alg *(*lookup)(const char *name, u32 type, u32 mask) = crypto_alg_mod_lookup; if (frontend) { type &= frontend->maskclear; mask &= frontend->maskclear; type |= frontend->type; mask |= frontend->maskset; if (frontend->lookup) lookup = frontend->lookup; } return lookup(alg_name, type, mask); } EXPORT_SYMBOL_GPL(crypto_find_alg); /* * crypto_alloc_tfm - Locate algorithm and allocate transform * @alg_name: Name of algorithm * @frontend: Frontend algorithm type * @type: Type of algorithm * @mask: Mask for type comparison * * crypto_alloc_tfm() will first attempt to locate an already loaded * algorithm. If that fails and the kernel supports dynamically loadable * modules, it will then attempt to load a module of the same name or * alias. If that fails it will send a query to any loaded crypto manager * to construct an algorithm on the fly. A refcount is grabbed on the * algorithm which is then associated with the new transform. * * The returned transform is of a non-determinate type. Most people * should use one of the more specific allocation functions such as * crypto_alloc_blkcipher. * * In case of error the return value is an error pointer. */ void *crypto_alloc_tfm(const char *alg_name, const struct crypto_type *frontend, u32 type, u32 mask) { void *tfm; int err; for (;;) { struct crypto_alg *alg; alg = crypto_find_alg(alg_name, frontend, type, mask); if (IS_ERR(alg)) { err = PTR_ERR(alg); goto err; } tfm = crypto_create_tfm(alg, frontend); if (!IS_ERR(tfm)) return tfm; crypto_mod_put(alg); err = PTR_ERR(tfm); err: if (err != -EAGAIN) break; if (fatal_signal_pending(current)) { err = -EINTR; break; } } return ERR_PTR(err); } EXPORT_SYMBOL_GPL(crypto_alloc_tfm); /* * crypto_destroy_tfm - Free crypto transform * @mem: Start of tfm slab * @tfm: Transform to free * * This function frees up the transform and any associated resources, * then drops the refcount on the associated algorithm. */ void crypto_destroy_tfm(void *mem, struct crypto_tfm *tfm) { struct crypto_alg *alg; if (unlikely(!mem)) return; alg = tfm->__crt_alg; if (!tfm->exit && alg->cra_exit) alg->cra_exit(tfm); crypto_exit_ops(tfm); crypto_mod_put(alg); kzfree(mem); } EXPORT_SYMBOL_GPL(crypto_destroy_tfm); int crypto_has_alg(const char *name, u32 type, u32 mask) { int ret = 0; struct crypto_alg *alg = crypto_alg_mod_lookup(name, type, mask); if (!IS_ERR(alg)) { crypto_mod_put(alg); ret = 1; } return ret; } EXPORT_SYMBOL_GPL(crypto_has_alg); MODULE_DESCRIPTION("Cryptographic core API"); MODULE_LICENSE("GPL");
tamnol/cs444-operating-systems-ii
project#3/api.c
C
gpl-2.0
13,986
<?php /** * @version $Id$ * @package Koowa_Template * @copyright Copyright (C) 2007 - 2012 Johan Janssens. All rights reserved. * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Abstract Template class * * @author Johan Janssens <johan@nooku.org> * @package Koowa_Template */ abstract class KTemplateAbstract extends KObject implements KTemplateInterface { /** * The template path * * @var string */ protected $_path; /** * The template data * * @var array */ protected $_data; /** * The template contents * * @var string */ protected $_content; /** * The set of template filters for templates * * @var array */ protected $_filters; /** * View object or identifier * * @var string|object */ protected $_view; /** * Counter * * Used to track recursive calls during template evaluation * * @var int * @see _evaluate() */ private $__counter; /** * Constructor * * Prevent creating instances of this class by making the constructor private * * @param KConfig $config An optional KConfig object with configuration options */ public function __construct(KConfig $config) { parent::__construct($config); // Set the view identifier $this->_view = $config->view; // Set the template data $this->_data = $config->data; // Mixin a command chain $this->mixin(new KMixinCommandchain($config->append(array('mixer' => $this)))); //Attach the filters $this->addFilter($config->filters); //Reset the counter $this->__counter = 0; } /** * Initializes the options for the object * * Called from {@link __construct()} as a first step of object instantiation. * * @param KConfig $config An optional KConfig object with configuration options. * @return void */ protected function _initialize(KConfig $config) { $config->append(array( 'data' => array(), 'filters' => array(), 'view' => null, 'command_chain' => new KCommandChain(), 'dispatch_events' => false, 'enable_callbacks' => false, )); parent::_initialize($config); } /** * Get the template path * * @return string */ public function getPath() { return $this->_path; } /** * Get the template data * * @return mixed */ public function getData() { return $this->_data; } /** * Get the template content * * @return string */ public function getContent() { return $this->_content; } /** * Get the view object attached to the template * * @throws \UnexpectedValueException If the views doesn't implement the KViewInterface * @return KViewInterface */ public function getView() { if(!$this->_view instanceof KViewAbstract) { //Make sure we have a view identifier if(!($this->_view instanceof KServiceIdentifier)) { $this->setView($this->_view); } $this->_view = $this->getService($this->_view); //Make sure the view implements KViewAbstract if(!$this->_view instanceof KViewAbstract) { throw new UnexpectedValueException( 'View: '.get_class($this->_view).' does not implement KViewInterface' ); } } return $this->_view; } /** * Method to set a view object attached to the controller * * @param mixed $view An object that implements KObjectServiceable, KServiceIdentifier object * or valid identifier string * @throws KTemplateException If the identifier is not a view identifier * @return KTemplateAbstract */ public function setView($view) { if(!($view instanceof KViewAbstract)) { if(empty($view) || (is_string($view) && strpos($view, '.') === false)) { $identifier = clone $this->getIdentifier(); $identifier->path = array('view'); if ($view) { $identifier->path[] = $view; } $identifier->name = KRequest::format() ? KRequest::format() : 'html'; } else $identifier = $this->getIdentifier($view); if($identifier->path[0] != 'view') { throw new KTemplateException('Identifier: '.$identifier.' is not a view identifier'); } $view = $identifier; } $this->_view = $view; return $this; } /** * Load a template by identifier * * This functions only accepts full identifiers of the format * - com:[//application/]component.view.[.path].name * * @param string The template identifier * @param array An associative array of data to be extracted in local template scope * @throws \InvalidArgumentException If the template could not be found * @return KTemplateAbstract */ public function loadIdentifier($template, $data = array()) { //Identify the template $identifier = $this->getIdentifier($template); // Find the template $file = $this->findFile(dirname($identifier->filepath).'/'.$identifier->name.'.php'); if ($file === false) { throw new InvalidArgumentException('Template "' . $identifier->name . '" not found'); } // Load the file $this->loadFile($file, $data); return $this; } /** * Load a template by path * * @param string $file The template path * @param array $data An associative array of data to be extracted in local template scope * @return KTemplateAbstract */ public function loadFile($path, $data = array()) { //Store the original path $this->_path = $path; //Get the file contents $contents = file_get_contents($path); //Load the contents $this->loadString($contents, $data); return $this; } /** * Load a template from a string * * @param string $string The template contents * @param array $data An associative array of data to be extracted in local template scope * @return KTemplateAbstract */ public function loadString($string, $data = array()) { $this->_content = $string; // Merge the data $this->_data = array_merge((array) $this->_data, $data); // Process inline templates if($this->__counter > 0) { $this->render(); } return $this; } /** * Render the template * * @return string The rendered data */ public function render() { //Parse the template $this->_parse($this->_content); //Evaluate the template $this->_evaluate($this->_content); //Process the template only at the end of the render cycle. if($this->__counter == 0) { $this->_process($this->_content); } return $this->_content; } /** * Check if the template is in a render cycle * * @return boolean Return TRUE if the template is being rendered */ public function isRendering() { return (bool) $this->_counter; } /** * Check if a filter exists * * @param string The name of the filter * @return boolean TRUE if the filter exists, FALSE otherwise */ public function hasFilter($filter) { return isset($this->_filters[$filter]); } /** * Adds one or more filters for template transformation * * @param array Array of one or more behaviors to add. * @return KTemplate */ public function addFilter($filters) { $filters = (array) KConfig::unbox($filters); foreach($filters as $filter) { if(!($filter instanceof KTemplateFilterInterface)) { $filter = $this->getFilter($filter); } //Enqueue the filter in the command chain $this->getCommandChain()->enqueue($filter); //Store the filter $this->_filters[$filter->getIdentifier()->name] = $filter; } return $this; } /** * Get a filter by identifier * * @return KTemplateFilterInterface */ public function getFilter($filter) { //Create the complete identifier if a partial identifier was passed if(is_string($filter) && strpos($filter, '.') === false ) { $identifier = clone $this->getIdentifier(); $identifier->path = array('template', 'filter'); $identifier->name = $filter; } else $identifier = KService::getIdentifier($filter); if (!isset($this->_filters[$identifier->name])) { $filter = KService::get($identifier); if(!($filter instanceof KTemplateFilterInterface)) { throw new KTemplateException("Template filter $identifier does not implement KTemplateFilterInterface"); } } else $filter = $this->_filters[$identifier->name]; return $filter; } /** * Get a template helper * * @param mixed KServiceIdentifierInterface * @return KTemplateHelperInterface */ public function getHelper($helper) { //Create the complete identifier if a partial identifier was passed if(is_string($helper) && strpos($helper, '.') === false ) { $identifier = clone $this->getIdentifier(); $identifier->path = array('template','helper'); $identifier->name = $helper; } else $identifier = $this->getIdentifier($helper); //Create the template helper $helper = $this->getService($identifier, array('template' => $this)); //Check the helper interface if(!($helper instanceof KTemplateHelperInterface)) { throw new KTemplateHelperException("Template helper $identifier does not implement KTemplateHelperInterface"); } return $helper; } /** * Load a template helper * * This functions accepts a partial identifier, in the form of helper.function. If a partial * identifier is passed a full identifier will be created using the template identifier. * * @param string Name of the helper, dot separated including the helper function to call * @param mixed Parameters to be passed to the helper * @return string Helper output */ public function renderHelper($identifier, $params = array()) { //Get the function to call based on the $identifier $parts = explode('.', $identifier); $function = array_pop($parts); $helper = $this->getHelper(implode('.', $parts)); //Call the helper function if (!is_callable( array( $helper, $function ) )) { throw new KTemplateHelperException( get_class($helper).'::'.$function.' not supported.' ); } return $helper->$function($params); } /** * Searches for the file * * @param string The file path to look for. * @return mixed The full path and file name for the target file, or FALSE * if the file is not found */ public function findFile($file) { $result = false; $path = dirname($file); // is the path based on a stream? if (strpos($path, '://') === false) { // not a stream, so do a realpath() to avoid directory // traversal attempts on the local file system. $path = realpath($path); // needed for substr() later $file = realpath($file); } // The substr() check added to make sure that the realpath() // results in a directory registered so that non-registered directores // are not accessible via directory traversal attempts. if (file_exists($file) && substr($file, 0, strlen($path)) == $path) { $result = $file; } // could not find the file in the set of paths return $result; } /** * Returns a directory path for temporary files * * @return string Folder path */ protected function _getTemporaryDirectory() { return JPATH_ROOT.'/tmp'; } /** * Creates a file with a unique file name * * @param string|null $directory Uses the result of _getTemporaryDirectory() by default * @return string File path */ protected function _getTemporaryFile($directory = null) { if ($directory === null) { $directory = $this->_getTemporaryDirectory(); } $name = str_replace('.', '', uniqid('tmpl', true)); $path = $directory.'/'.$name; touch($path); return $path; } /** * Parse and compile the template to PHP code * * This function passes the template through read filter chain and returns the result. * * @return string The parsed data */ protected function _parse(&$content) { $context = $this->getCommandContext(); $context->data = $content; $this->getCommandChain()->run(KTemplateFilter::MODE_READ, $context); $content = $context->data; } /** * Evaluate the template using a simple sandbox * * This function writes the template to a temporary file and then includes it. * * @return string The evaluated data * @see tempnam() */ protected function _evaluate(&$content) { //Increase counter $this->__counter++; //Create temporary file $tempfile = $this->_getTemporaryFile(); //Write the template to the file $handle = fopen($tempfile, "w+"); fwrite($handle, $content); fclose($handle); //Include the file extract($this->_data, EXTR_SKIP); ob_start(); include $tempfile; $content = ob_get_clean(); unlink($tempfile); //Reduce counter $this->__counter--;; } /** * Process the template * * This function passes the template through write filter chain and returns the result. * * @return string The rendered data */ protected function _process(&$content) { $context = $this->getCommandContext(); $context->data = $content; $this->getCommandChain()->run(KTemplateFilter::MODE_WRITE, $context); $content = $context->data; } /** * Returns the template contents * * @return string * @see getContents() */ public function __toString() { return $this->getContent(); } }
dwarkeshsoni/jsn_time_free_j3x
libraries/koowa/template/abstract.php
PHP
gpl-2.0
14,969
# -*- coding: utf-8 -*- # Copyright(c) 2016-2020 Jonas Sjöberg <autonameow@jonasjberg.com> # Source repository: https://github.com/jonasjberg/autonameow # # This file is part of autonameow. # # autonameow 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. # # autonameow 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 autonameow. If not, see <http://www.gnu.org/licenses/>. import logging from collections import defaultdict from core import event from core import logs from core.datastore import repository from core.datastore.query import QueryResponseFailure from core.exceptions import AutonameowException from core.model import genericfields from util import sanity log = logging.getLogger(__name__) def _map_generic_sources(meowuri_class_map): """ Returns a dict keyed by provider classes storing sets of "generic" fields as Unicode strings. """ klass_generic_meowuris_map = defaultdict(set) for _, klass in meowuri_class_map.items(): # TODO: [TD0151] Fix inconsistent use of classes/instances. # TODO: [TD0157] Look into analyzers 'FIELD_LOOKUP' attributes. for _, field_metainfo in klass.metainfo().items(): generic_field_string = field_metainfo.get('generic_field') if not generic_field_string: continue assert isinstance(generic_field_string, str) generic_field_klass = genericfields.get_field_for_uri_leaf(generic_field_string) if not generic_field_klass: continue assert issubclass(generic_field_klass, genericfields.GenericField) generic_meowuri = generic_field_klass.uri() if not generic_meowuri: continue klass_generic_meowuris_map[klass].add(generic_meowuri) return klass_generic_meowuris_map def _get_meowuri_source_map(): """ Returns a dict mapping "MeowURIs" to provider classes. Example return value: { 'extractor.filesystem.xplat': CrossPlatformFilesystemExtractor, 'extractor.metadata.exiftool': ExiftoolMetadataExtractor, } Returns: Dictionary keyed by instances of the 'MeowURI' class, storing provider classes. """ import analyzers import extractors mapping = dict() for module_name in (analyzers, extractors): module_registry = getattr(module_name, 'registry') klass_list = module_registry.all_providers for klass in klass_list: uri = klass.meowuri_prefix() assert uri, 'Got empty "meowuri_prefix" from {!s}'.format(klass) assert uri not in mapping, 'URI "{!s}" already mapped'.format(uri) mapping[uri] = klass return mapping def _get_excluded_sources(): """ Returns a set of provider classes excluded due to unmet dependencies. """ import extractors import analyzers all_excluded = set() for module_name in (analyzers, extractors): module_registry = getattr(module_name, 'registry') all_excluded.update(module_registry.excluded_providers) return all_excluded class ProviderRegistry(object): def __init__(self, meowuri_source_map, excluded_providers): self.log = logging.getLogger( '{!s}.{!s}'.format(__name__, self.__module__) ) self.meowuri_sources = dict(meowuri_source_map) self._debug_log_mapped_meowuri_sources() self._excluded_providers = excluded_providers # Set of all MeowURIs "registered" by extractors or analyzers. self.mapped_meowuris = self.unique_map_meowuris(self.meowuri_sources) # Providers declaring generic MeowURIs through 'metainfo()'. self.generic_meowuri_sources = _map_generic_sources(self.meowuri_sources) self._debug_log_mapped_generic_meowuri_sources() @property def excluded_providers(self): # Sort here so that callers won't have to work around the possibility # of excluded providers not having a common base class and thus being # unorderable. return sorted(self._excluded_providers, key=lambda x: x.__name__) def _debug_log_mapped_meowuri_sources(self): if not logs.DEBUG: return for uri, klass in sorted(self.meowuri_sources.items()): self.log.debug('Mapped MeowURI "%s" to %s', uri, klass.name()) def _debug_log_mapped_generic_meowuri_sources(self): if not logs.DEBUG: return for klass, uris in self.generic_meowuri_sources.items(): klass_name = klass.name() for uri in sorted(uris): self.log.debug('Mapped generic MeowURI "%s" to %s', uri, klass_name) def might_be_resolvable(self, uri): if not uri: return False sanity.check_isinstance_meowuri(uri) resolvable = list(self.mapped_meowuris) uri_without_leaf = uri.stripleaf() return any(m.matches_start(uri_without_leaf) for m in resolvable) def providers_for_meowuri(self, requested_meowuri): """ Returns a set of classes that might store data under a given "MeowURI". Note that the provider "MeowURI" is matched as a substring of the requested "MeowURI". Args: requested_meowuri: The "MeowURI" of interest. Returns: A set of classes that "could" produce and store data under a "MeowURI" that is a substring of the given "MeowURI". """ found = set() if not requested_meowuri: self.log.error('"providers_for_meowuri()" got empty MeowURI!') return found if requested_meowuri.is_generic: found = self._providers_for_generic_meowuri(requested_meowuri) else: found = self._source_providers_for_meowuri(requested_meowuri) self.log.debug('%s returning %d providers for MeowURI %s', self.__class__.__name__, len(found), requested_meowuri) return found def _providers_for_generic_meowuri(self, requested_meowuri): found = set() for klass, meowuris in self.generic_meowuri_sources.items(): if requested_meowuri in meowuris: found.add(klass) return found def _source_providers_for_meowuri(self, requested_meowuri): # Argument 'requested_meowuri' is a full "source-specific" MeowURI, # like 'extractor.metadata.exiftool.EXIF:CreateDate' requested_meowuri_without_leaf = requested_meowuri.stripleaf() found = set() for uri in self.meowuri_sources.keys(): # 'uri' is a "MeowURI root" ('extractor.metadata.epub') if uri.matches_start(requested_meowuri_without_leaf): found.add(self.meowuri_sources[uri]) return found @staticmethod def unique_map_meowuris(meowuri_class_map): unique_meowuris = set() for uri in meowuri_class_map.keys(): unique_meowuris.add(uri) return unique_meowuris class ProviderRunner(object): def __init__(self, config, extractor_runner, run_analysis_func): self.config = config self._extractor_runner = extractor_runner assert callable(run_analysis_func), ( 'Expected dependency-injected "run_analysis" to be callable' ) self._run_analysis = run_analysis_func self._provider_delegation_history = defaultdict(set) self._delegate_every_possible_meowuri_history = set() def delegate_to_providers(self, fileobject, uri): possible_providers = set(Registry.providers_for_meowuri(uri)) if not possible_providers: log.debug('Got no possible providers for delegation %s', uri) return # TODO: [TD0161] Translate from specific to "generic" MeowURI? # Might be useful to be able to translate a specific MeowURI like # 'analyzer.ebook.title' to a "generic" like 'generic.metadata.title'. # Otherwise, user is almost never prompted with any possible candidates. prepared_analyzers = set() prepared_extractors = set() num_possible_providers = len(possible_providers) for n, provider in enumerate(possible_providers, start=1): log.debug('Looking at possible provider (%d/%d): %s', n, num_possible_providers, provider) if self._previously_delegated_provider(fileobject, provider): log.debug('Skipping previously delegated provider %s', provider) continue self._remember_provider_delegation(fileobject, provider) if _provider_is_extractor(provider): prepared_extractors.add(provider) elif _provider_is_analyzer(provider): prepared_analyzers.add(provider) if prepared_extractors: log.debug('Delegating %s to extractors: %s', uri, prepared_extractors) self._delegate_to_extractors(fileobject, prepared_extractors) if prepared_analyzers: log.debug('Delegating %s to analyzers: %s', uri, prepared_analyzers) self._delegate_to_analyzers(fileobject, prepared_analyzers) def _previously_delegated_provider(self, fileobject, provider): if fileobject in self._delegate_every_possible_meowuri_history: return True return bool( fileobject in self._provider_delegation_history and provider in self._provider_delegation_history[fileobject] ) def _remember_provider_delegation(self, fileobject, provider): self._provider_delegation_history[fileobject].add(provider) def _delegate_to_extractors(self, fileobject, extractors_to_run): try: self._extractor_runner.start(fileobject, extractors_to_run) except AutonameowException as e: # TODO: [TD0164] Tidy up throwing/catching of exceptions. log.critical('Extraction FAILED: %s', e) raise def _delegate_to_analyzers(self, fileobject, analyzers_to_run): self._run_analysis( fileobject, self.config, analyzers_to_run=analyzers_to_run ) def delegate_every_possible_meowuri(self, fileobject): self._delegate_every_possible_meowuri_history.add(fileobject) # Run all extractors try: self._extractor_runner.start(fileobject, request_all=True) except AutonameowException as e: # TODO: [TD0164] Tidy up throwing/catching of exceptions. log.critical('Extraction FAILED: %s', e) raise # Run all analyzers self._run_analysis(fileobject, self.config) def _provider_is_extractor(provider): # TODO: [hack] Fix circular import problems when running new unit test runner. # $ PYTHONPATH=autonameow:tests python3 -m unit --skip-slow from extractors.metadata.base import BaseMetadataExtractor return issubclass(provider, BaseMetadataExtractor) def _provider_is_analyzer(provider): # TODO: [hack] Fix circular import problems when running new unit test runner. # $ PYTHONPATH=autonameow:tests python3 -m unit --skip-slow from analyzers import BaseAnalyzer return issubclass(provider, BaseAnalyzer) class MasterDataProvider(object): """ Handles top-level _DYNAMIC_ data retrieval and data extraction delegation. This is one of two main means of querying for data related to a file. Compared to the repository, which is a static storage that either contain the requested data or not, this is a "reactive" interface to the repository. If the requested data is in the repository, is it retrieved and returned. Otherwise, data providers (extractors/analyzers) that might be able to provide the requested data is executed. If the execution turns up the requested data, it is returned. This is intended to be a "dynamic" or "reactive" data retrieval interface for use by any part of the application. """ def __init__(self, config, run_analysis_func): self.config = config assert repository.SessionRepository is not None, ( 'Expected Repository to be initialized at this point' ) from core.extraction import ExtractorRunner extractor_runner = ExtractorRunner( add_results_callback=repository.SessionRepository.store ) assert hasattr(extractor_runner, 'start'), ( 'Expected "ExtractorRunner" to have an attribute "start"' ) self.provider_runner = ProviderRunner( self.config, extractor_runner, run_analysis_func ) def delegate_every_possible_meowuri(self, fileobject): log.debug('Running all available providers for %r', fileobject) self.provider_runner.delegate_every_possible_meowuri(fileobject) def request(self, fileobject, uri): """ Highest-level retrieval mechanism for data related to a file. First the repository is queried with the MeowURI and if the query returns data, it is returned. If the data is not in the repository, the task of gathering the data is delegated to the "relevant" providers. Then the repository is queried again. If the delegation "succeeded" and the sought after data could be gathered, it would now be stored in the repository and passed back as the return value. None is returned if nothing turns up. """ log.debug('Got request %r->[%s]', fileobject, uri) # First try the repository for previously gathered data response = self._query_repository(fileobject, uri) if response: return response # Have relevant providers gather the data self._delegate_to_providers(fileobject, uri) # Try the repository again response = self._query_repository(fileobject, uri) if response: return response log.debug('Failed query, then delegation, then another query and returning None') return QueryResponseFailure( fileobject=fileobject, uri=uri, msg='Repository query -> Delegation -> Repository query' ) def request_one(self, fileobject, uri): # TODO: [TD0175] Handle requesting exactly one or multiple alternatives. response = self.request(fileobject, uri) if isinstance(response, list): if len(response) == 1: return response[0] return QueryResponseFailure( fileobject=fileobject, uri=uri, msg='Requested one but response contains {}'.format(len(response)) ) return response def _delegate_to_providers(self, fileobject, uri): log.debug('Delegating request to providers: %r->[%s]', fileobject, uri) self.provider_runner.delegate_to_providers(fileobject, uri) def _query_repository(self, fileobject, uri): return repository.SessionRepository.query(fileobject, uri) _MASTER_DATA_PROVIDER = None def _initialize_master_data_provider(*_, **kwargs): active_config = kwargs.get('config') from core import analysis run_analysis_func = analysis.run_analysis # Keep one global 'MasterDataProvider' singleton per 'Autonameow' instance. global _MASTER_DATA_PROVIDER _MASTER_DATA_PROVIDER = MasterDataProvider(active_config, run_analysis_func) def _shutdown_master_data_provider(*_, **__): # TODO: [TD0202] Handle signals and graceful shutdown properly! global _MASTER_DATA_PROVIDER _MASTER_DATA_PROVIDER = None Registry = None def _initialize_provider_registry(*_, **__): # Keep one global 'ProviderRegistry' singleton per 'Autonameow' instance. global Registry if not Registry: Registry = ProviderRegistry( meowuri_source_map=_get_meowuri_source_map(), excluded_providers=_get_excluded_sources() ) def _shutdown_provider_registry(*_, **__): # TODO: [TD0202] Handle signals and graceful shutdown properly! global Registry Registry = None event.dispatcher.on_config_changed.add(_initialize_master_data_provider) event.dispatcher.on_startup.add(_initialize_provider_registry) event.dispatcher.on_shutdown.add(_shutdown_provider_registry) event.dispatcher.on_shutdown.add(_shutdown_master_data_provider) def request(fileobject, uri): sanity.check_isinstance_meowuri(uri) return _MASTER_DATA_PROVIDER.request(fileobject, uri) def request_one(fileobject, uri): sanity.check_isinstance_meowuri(uri) return _MASTER_DATA_PROVIDER.request_one(fileobject, uri) def delegate_every_possible_meowuri(fileobject): _MASTER_DATA_PROVIDER.delegate_every_possible_meowuri(fileobject)
jonasjberg/autonameow
autonameow/core/master_provider.py
Python
gpl-2.0
17,265
#include <2geom/sbasis-geometric.h> #include <2geom/sbasis.h> #include <2geom/sbasis-math.h> //#include <2geom/solver.h> #include <2geom/sbasis-geometric.h> /** Geometric operators on D2<SBasis> (1D->2D). * Copyright 2007 JF Barraud * Copyright 2007 N Hurst * * The functions defined in this header related to 2d geometric operations such as arc length, * unit_vector, curvature, and centroid. Most are built on top of unit_vector, which takes an * arbitrary D2 and returns a D2 with unit length with the same direction. * * Todo/think about: * arclength D2 -> sbasis (giving arclength function) * does uniform_speed return natural parameterisation? * integrate sb2d code from normal-bundle * angle(md<2>) -> sbasis (gives angle from vector - discontinuous?) * osculating circle center? * **/ //namespace Geom{ using namespace Geom; using namespace std; //Some utils first. //TODO: remove this!! /** * Return a list of doubles that appear in both a and b to within error tol * a, b, vector of double * tol tolerance */ static vector<double> vect_intersect(vector<double> const &a, vector<double> const &b, double tol=0.){ vector<double> inter; unsigned i=0,j=0; while ( i<a.size() && j<b.size() ){ if (fabs(a[i]-b[j])<tol){ inter.push_back(a[i]); i+=1; j+=1; }else if (a[i]<b[j]){ i+=1; }else if (a[i]>b[j]){ j+=1; } } return inter; } //------------------------------------------------------------------------------ static SBasis divide_by_sk(SBasis const &a, int k) { if ( k>=(int)a.size()){ //make sure a is 0? return SBasis(); } if(k < 0) return shift(a,-k); SBasis c; c.insert(c.begin(), a.begin()+k, a.end()); return c; } static SBasis divide_by_t0k(SBasis const &a, int k) { if(k < 0) { SBasis c = Linear(0,1); for (int i=2; i<=-k; i++){ c*=c; } c*=a; return(c); }else{ SBasis c = Linear(1,0); for (int i=2; i<=k; i++){ c*=c; } c*=a; return(divide_by_sk(c,k)); } } static SBasis divide_by_t1k(SBasis const &a, int k) { if(k < 0) { SBasis c = Linear(1,0); for (int i=2; i<=-k; i++){ c*=c; } c*=a; return(c); }else{ SBasis c = Linear(0,1); for (int i=2; i<=k; i++){ c*=c; } c*=a; return(divide_by_sk(c,k)); } } static D2<SBasis> RescaleForNonVanishingEnds(D2<SBasis> const &MM, double ZERO=1.e-4){ D2<SBasis> M = MM; //TODO: divide by all the s at once!!! while ((M[0].size()>0||M[1].size()>0) && fabs(M[0].at0())<ZERO && fabs(M[1].at0())<ZERO && fabs(M[0].at1())<ZERO && fabs(M[1].at1())<ZERO){ M[0] = divide_by_sk(M[0],1); M[1] = divide_by_sk(M[1],1); } while ((M[0].size()>0||M[1].size()>0) && fabs(M[0].at0())<ZERO && fabs(M[1].at0())<ZERO){ M[0] = divide_by_t0k(M[0],1); M[1] = divide_by_t0k(M[1],1); } while ((M[0].size()>0||M[1].size()>0) && fabs(M[0].at1())<ZERO && fabs(M[1].at1())<ZERO){ M[0] = divide_by_t1k(M[0],1); M[1] = divide_by_t1k(M[1],1); } return M; } /*static D2<SBasis> RescaleForNonVanishing(D2<SBasis> const &MM, double ZERO=1.e-4){ std::vector<double> levels; levels.push_back(-ZERO); levels.push_back(ZERO); //std::vector<std::vector<double> > mr = multi_roots(MM, levels); }*/ //================================================================= //TODO: what's this for?!?! Piecewise<D2<SBasis> > Geom::cutAtRoots(Piecewise<D2<SBasis> > const &M, double ZERO){ vector<double> rts; for (unsigned i=0; i<M.size(); i++){ vector<double> seg_rts = roots((M.segs[i])[0]); seg_rts = vect_intersect(seg_rts, roots((M.segs[i])[1]), ZERO); Linear mapToDom = Linear(M.cuts[i],M.cuts[i+1]); for (unsigned r=0; r<seg_rts.size(); r++){ seg_rts[r]= mapToDom(seg_rts[r]); } rts.insert(rts.end(),seg_rts.begin(),seg_rts.end()); } return partition(M,rts); } /** Return a function which gives the angle of vect at each point. \param vect a piecewise parameteric curve. \param tol the maximum error allowed. \param order the maximum degree to use for approximation */ Piecewise<SBasis> Geom::atan2(Piecewise<D2<SBasis> > const &vect, double tol, unsigned order){ Piecewise<SBasis> result; Piecewise<D2<SBasis> > v = cutAtRoots(vect,tol); result.cuts.push_back(v.cuts.front()); for (unsigned i=0; i<v.size(); i++){ D2<SBasis> vi = RescaleForNonVanishingEnds(v.segs[i]); SBasis x=vi[0], y=vi[1]; Piecewise<SBasis> angle; angle = divide (x*derivative(y)-y*derivative(x), x*x+y*y, tol, order); //TODO: I don't understand this - sign. angle = integral(-angle); Point vi0 = vi.at0(); angle += -std::atan2(vi0[1],vi0[0]) - angle[0].at0(); //TODO: deal with 2*pi jumps form one seg to the other... //TODO: not exact at t=1 because of the integral. //TODO: force continuity? angle.setDomain(Interval(v.cuts[i],v.cuts[i+1])); result.concat(angle); } return result; } /** Return a function which gives the angle of vect at each point. \param vect a piecewise parameteric curve. \param tol the maximum error allowed. \param order the maximum degree to use for approximation */ Piecewise<SBasis> Geom::atan2(D2<SBasis> const &vect, double tol, unsigned order){ return atan2(Piecewise<D2<SBasis> >(vect),tol,order); } /** tan2 is the pseudo-inverse of atan2. It takes an angle and returns a unit_vector that points in the direction of angle. \param angle a piecewise function of angle wrt t. \param tol the maximum error allowed. \param order the maximum degree to use for approximation */ D2<Piecewise<SBasis> > Geom::tan2(SBasis const &angle, double tol, unsigned order){ return tan2(Piecewise<SBasis>(angle), tol, order); } /** tan2 is the pseudo-inverse of atan2. It takes an angle and returns a unit_vector that points in the direction of angle. \param angle a piecewise function of angle wrt t. \param tol the maximum error allowed. \param order the maximum degree to use for approximation */ D2<Piecewise<SBasis> > Geom::tan2(Piecewise<SBasis> const &angle, double tol, unsigned order){ return D2<Piecewise<SBasis> >(cos(angle, tol, order), sin(angle, tol, order)); } /** Return a Piecewise<D2<SBasis> > which points in the same direction as V_in, but has unit_length. \param V_in the original path. \param tol the maximum error allowed. \param order the maximum degree to use for approximation unitVector(x,y) is computed as (b,-a) where a and b are solutions of: ax+by=0 (eqn1) and a^2+b^2=1 (eqn2) */ Piecewise<D2<SBasis> > Geom::unitVector(D2<SBasis> const &V_in, double tol, unsigned order){ //TODO: Handle vanishing vectors... // -This approach is numerically bad. Find a stable way to rescale V_in to have non vanishing ends. // -This done, unitVector will have jumps at zeros: fill the gaps with arcs of circles. D2<SBasis> V = RescaleForNonVanishingEnds(V_in); if (V[0].empty() && V[1].empty()) return Piecewise<D2<SBasis> >(D2<SBasis>(Linear(1),SBasis())); SBasis x = V[0], y = V[1]; SBasis r_eqn1, r_eqn2; Point v0 = unit_vector(V.at0()); Point v1 = unit_vector(V.at1()); SBasis a = SBasis(order+1, Linear(0.)); a[0] = Linear(-v0[1],-v1[1]); SBasis b = SBasis(order+1, Linear(0.)); b[0] = Linear( v0[0], v1[0]); r_eqn1 = -(a*x+b*y); r_eqn2 = Linear(1.)-(a*a+b*b); for (unsigned k=1; k<=order; k++){ double r0 = (k<r_eqn1.size())? r_eqn1.at(k).at0() : 0; double r1 = (k<r_eqn1.size())? r_eqn1.at(k).at1() : 0; double rr0 = (k<r_eqn2.size())? r_eqn2.at(k).at0() : 0; double rr1 = (k<r_eqn2.size())? r_eqn2.at(k).at1() : 0; double a0,a1,b0,b1;// coeffs in a[k] and b[k] //the equations to solve at this point are: // a0*x(0)+b0*y(0)=r0 & 2*a0*a(0)+2*b0*b(0)=rr0 //and // a1*x(1)+b1*y(1)=r1 & 2*a1*a(1)+2*b1*b(1)=rr1 a0 = r0/dot(v0,V.at0())*v0[0]-rr0/2*v0[1]; b0 = r0/dot(v0,V.at0())*v0[1]+rr0/2*v0[0]; a1 = r1/dot(v1,V.at1())*v1[0]-rr1/2*v1[1]; b1 = r1/dot(v1,V.at1())*v1[1]+rr1/2*v1[0]; a[k] = Linear(a0,a1); b[k] = Linear(b0,b1); //TODO: use "incremental" rather than explicit formulas. r_eqn1 = -(a*x+b*y); r_eqn2 = Linear(1)-(a*a+b*b); } //our candidate is: D2<SBasis> unitV; unitV[0] = b; unitV[1] = -a; //is it good? double rel_tol = std::max(1.,std::max(V_in[0].tailError(0),V_in[1].tailError(0)))*tol; if (r_eqn1.tailError(order)>rel_tol || r_eqn2.tailError(order)>tol){ //if not: subdivide and concat results. Piecewise<D2<SBasis> > unitV0, unitV1; unitV0 = unitVector(compose(V,Linear(0,.5)),tol,order); unitV1 = unitVector(compose(V,Linear(.5,1)),tol,order); unitV0.setDomain(Interval(0.,.5)); unitV1.setDomain(Interval(.5,1.)); unitV0.concat(unitV1); return(unitV0); }else{ //if yes: return it as pw. Piecewise<D2<SBasis> > result; result=(Piecewise<D2<SBasis> >)unitV; return result; } } /** Return a Piecewise<D2<SBasis> > which points in the same direction as V_in, but has unit_length. \param V_in the original path. \param tol the maximum error allowed. \param order the maximum degree to use for approximation unitVector(x,y) is computed as (b,-a) where a and b are solutions of: ax+by=0 (eqn1) and a^2+b^2=1 (eqn2) */ Piecewise<D2<SBasis> > Geom::unitVector(Piecewise<D2<SBasis> > const &V, double tol, unsigned order){ Piecewise<D2<SBasis> > result; Piecewise<D2<SBasis> > VV = cutAtRoots(V); result.cuts.push_back(VV.cuts.front()); for (unsigned i=0; i<VV.size(); i++){ Piecewise<D2<SBasis> > unit_seg; unit_seg = unitVector(VV.segs[i],tol, order); unit_seg.setDomain(Interval(VV.cuts[i],VV.cuts[i+1])); result.concat(unit_seg); } return result; } /** returns a function giving the arclength at each point in M. \param M the Element. \param tol the maximum error allowed. */ Piecewise<SBasis> Geom::arcLengthSb(Piecewise<D2<SBasis> > const &M, double tol){ Piecewise<D2<SBasis> > dM = derivative(M); Piecewise<SBasis> dMlength = sqrt(dot(dM,dM),tol,3); Piecewise<SBasis> length = integral(dMlength); length-=length.segs.front().at0(); return length; } /** returns a function giving the arclength at each point in M. \param M the Element. \param tol the maximum error allowed. */ Piecewise<SBasis> Geom::arcLengthSb(D2<SBasis> const &M, double tol){ return arcLengthSb(Piecewise<D2<SBasis> >(M), tol); } #if 0 double Geom::length(D2<SBasis> const &M, double tol){ Piecewise<SBasis> length = arcLengthSb(M, tol); return length.segs.back().at1(); } double Geom::length(Piecewise<D2<SBasis> > const &M, double tol){ Piecewise<SBasis> length = arcLengthSb(M, tol); return length.segs.back().at1(); } #endif /** returns a function giving the curvature at each point in M. \param M the Element. \param tol the maximum error allowed. Todo: * claimed incomplete. Check. */ Piecewise<SBasis> Geom::curvature(D2<SBasis> const &M, double tol) { D2<SBasis> dM=derivative(M); Piecewise<SBasis> result; Piecewise<D2<SBasis> > unitv = unitVector(dM,tol); Piecewise<SBasis> dMlength = dot(Piecewise<D2<SBasis> >(dM),unitv); Piecewise<SBasis> k = cross(derivative(unitv),unitv); k = divide(k,dMlength,tol,3); return(k); } /** returns a function giving the curvature at each point in M. \param M the Element. \param tol the maximum error allowed. Todo: * claimed incomplete. Check. */ Piecewise<SBasis> Geom::curvature(Piecewise<D2<SBasis> > const &V, double tol){ Piecewise<SBasis> result; Piecewise<D2<SBasis> > VV = cutAtRoots(V); result.cuts.push_back(VV.cuts.front()); for (unsigned i=0; i<VV.size(); i++){ Piecewise<SBasis> curv_seg; curv_seg = curvature(VV.segs[i],tol); curv_seg.setDomain(Interval(VV.cuts[i],VV.cuts[i+1])); result.concat(curv_seg); } return result; } //================================================================= /** Reparameterise M to have unit speed. \param M the Element. \param tol the maximum error allowed. \param order the maximum degree to use for approximation */ Piecewise<D2<SBasis> > Geom::arc_length_parametrization(D2<SBasis> const &M, unsigned order, double tol){ Piecewise<D2<SBasis> > u; u.push_cut(0); Piecewise<SBasis> s = arcLengthSb(Piecewise<D2<SBasis> >(M),tol); for (unsigned i=0; i < s.size();i++){ double t0=s.cuts[i],t1=s.cuts[i+1]; D2<SBasis> sub_M = compose(M,Linear(t0,t1)); D2<SBasis> sub_u; for (unsigned dim=0;dim<2;dim++){ SBasis sub_s = s.segs[i]; sub_s-=sub_s.at0(); sub_s/=sub_s.at1(); sub_u[dim]=compose_inverse(sub_M[dim],sub_s, order, tol); } u.push(sub_u,s(t1)); } return u; } /** Reparameterise M to have unit speed. \param M the Element. \param tol the maximum error allowed. \param order the maximum degree to use for approximation */ Piecewise<D2<SBasis> > Geom::arc_length_parametrization(Piecewise<D2<SBasis> > const &M, unsigned order, double tol){ Piecewise<D2<SBasis> > result; for (unsigned i=0; i<M.size(); i++ ){ Piecewise<D2<SBasis> > uniform_seg=arc_length_parametrization(M[i],order,tol); result.concat(uniform_seg); } return(result); } #include <gsl/gsl_integration.h> static double sb_length_integrating(double t, void* param) { SBasis* pc = (SBasis*)param; return sqrt((*pc)(t)); } /** Calculates the length of a D2<SBasis> through gsl integration. \param B the Element. \param tol the maximum error allowed. \param result variable to be incremented with the length of the path \param abs_error variable to be incremented with the estimated error If you only want the length, this routine may be faster/more accurate. */ void Geom::length_integrating(D2<SBasis> const &B, double &result, double &abs_error, double tol) { D2<SBasis> dB = derivative(B); SBasis dB2 = dot(dB, dB); gsl_function F; gsl_integration_workspace * w = gsl_integration_workspace_alloc (20); F.function = &sb_length_integrating; F.params = (void*)&dB2; double quad_result, err; /* We could probably use the non adaptive code here if we removed any cusps first. */ gsl_integration_qag (&F, 0, 1, 0, tol, 20, GSL_INTEG_GAUSS21, w, &quad_result, &err); abs_error += err; result += quad_result; } /** Calculates the length of a D2<SBasis> through gsl integration. \param s the Element. \param tol the maximum error allowed. If you only want the total length, this routine faster and more accurate than constructing an arcLengthSb. */ double Geom::length(D2<SBasis> const &s, double tol){ double result = 0; double abs_error = 0; length_integrating(s, result, abs_error, tol); return result; } /** Calculates the length of a Piecewise<D2<SBasis> > through gsl integration. \param s the Element. \param tol the maximum error allowed. If you only want the total length, this routine faster and more accurate than constructing an arcLengthSb. */ double Geom::length(Piecewise<D2<SBasis> > const &s, double tol){ double result = 0; double abs_error = 0; for (unsigned i=0; i < s.size();i++){ length_integrating(s[i], result, abs_error, tol); } return result; } /** * Centroid using sbasis integration. \param p the Element. \param centroid on return contains the centroid of the shape \param area on return contains the signed area of the shape. This approach uses green's theorem to compute the area and centroid using integrals. For curved shapes this is much faster than converting to polyline. Note that without an uncross operation the output is not the absolute area. * Returned values: 0 for normal execution; 2 if area is zero, meaning centroid is meaningless. */ unsigned Geom::centroid(Piecewise<D2<SBasis> > const &p, Point& centroid, double &area) { Point centroid_tmp(0,0); double atmp = 0; for(unsigned i = 0; i < p.size(); i++) { SBasis curl = dot(p[i], rot90(derivative(p[i]))); SBasis A = integral(curl); D2<SBasis> C = integral(multiply(curl, p[i])); atmp += A.at1() - A.at0(); centroid_tmp += C.at1()- C.at0(); // first moment. } // join ends centroid_tmp *= 2; Point final = p[p.size()-1].at1(), initial = p[0].at0(); const double ai = cross(final, initial); atmp += ai; centroid_tmp += (final + initial)*ai; // first moment. area = atmp / 2; if (atmp != 0) { centroid = centroid_tmp / (3 * atmp); return 0; } return 2; } /** * Find cubics with prescribed curvatures at both ends. * * this requires to solve a system of the form * * \f[ * \lambda_1 = a_0 \lambda_0^2 + c_0 * \lambda_0 = a_1 \lambda_1^2 + c_1 * \f] * * which is a deg 4 equation in lambda 0. * Below are basic functions dedicated to solving this assuming a0 and a1 !=0. */ static OptInterval find_bounds_for_lambda0(double aa0,double aa1,double cc0,double cc1, int insist_on_speeds_signs){ double a0=aa0,a1=aa1,c0=cc0,c1=cc1; Interval result; bool flip = a1<0; if (a1<0){a1=-a1; c1=-c1;} if (a0<0){a0=-a0; c0=-c0;} double a = (a0<a1 ? a0 : a1); double c = (c0<c1 ? c0 : c1); double delta = 1-4*a*c; if ( delta < 0 ) return OptInterval();//return empty interval double lambda_max = (1+std::sqrt(delta))/2/a; result = Interval(c,lambda_max); if (flip) result *= -1; if (insist_on_speeds_signs == 1){ if (result.max() < 0)//Caution: setMin with max<new min... return OptInterval();//return empty interval result.setMin(0); } result = Interval(result.min()-.1,result.max()+.1);//just in case all our approx. were exact... return result; } static std::vector<double> solve_lambda0(double a0,double a1,double c0,double c1, int insist_on_speeds_signs){ SBasis p(3, Linear()); p[0] = Linear( a1*c0*c0+c1, a1*a0*(a0+ 2*c0) +a1*c0*c0 +c1 -1 ); p[1] = Linear( -a1*a0*(a0+2*c0), -a1*a0*(3*a0+2*c0) ); p[2] = Linear( a1*a0*a0 ); OptInterval domain = find_bounds_for_lambda0(a0,a1,c0,c1,insist_on_speeds_signs); if ( !domain ) return std::vector<double>(); p = compose(p,Linear(domain->min(),domain->max())); std::vector<double>rts = roots(p); for (unsigned i=0; i<rts.size(); i++){ rts[i] = domain->min() + rts[i] * domain->extent(); } return rts; } /** * \brief returns the cubics fitting direction and curvature of a given * input curve at two points. * * The input can be the * value, speed, and acceleration * or * value, speed, and cross(acceleration,speed) * of the original curve at the both ends. * (the second is often technically usefull, as it avoids unnecessary division by |v|^2) * Recall that K=1/R=cross(acceleration,speed)/|speed|^3. * * Moreover, a 7-th argument 'insist_on_speed_signs' can be supplied to select solutions: * If insist_on_speed_signs == 1, only consider solutions where speeds at both ends are positively * proportional to the given ones. * If insist_on_speed_signs == 0, allow speeds to point in the opposite direction (both at the same time) * If insist_on_speed_signs == -1, allow speeds to point in both direction independantly. */ std::vector<D2<SBasis> > Geom::cubics_fitting_curvature(Point const &M0, Point const &M1, Point const &dM0, Point const &dM1, double d2M0xdM0, double d2M1xdM1, int insist_on_speed_signs, double epsilon){ std::vector<D2<SBasis> > result; //speed of cubic bezier will be lambda0*dM0 and lambda1*dM1, //with lambda0 and lambda1 s.t. curvature at both ends is the same //as the curvature of the given curve. std::vector<double> lambda0,lambda1; double dM1xdM0=cross(dM1,dM0); if (fabs(dM1xdM0)<epsilon){ if (fabs(d2M0xdM0)<epsilon || fabs(d2M1xdM1)<epsilon){ return result; } double lbda02 = 6.*cross(M1-M0,dM0)/d2M0xdM0; double lbda12 =-6.*cross(M1-M0,dM1)/d2M1xdM1; if (lbda02<0 || lbda12<0){ return result; } lambda0.push_back(std::sqrt(lbda02) ); lambda1.push_back(std::sqrt(lbda12) ); }else{ //solve: lambda1 = a0 lambda0^2 + c0 // lambda0 = a1 lambda1^2 + c1 double a0,c0,a1,c1; a0 = -d2M0xdM0/2/dM1xdM0; c0 = 3*cross(M1-M0,dM0)/dM1xdM0; a1 = -d2M1xdM1/2/dM1xdM0; c1 = -3*cross(M1-M0,dM1)/dM1xdM0; if (fabs(a0)<epsilon){ lambda1.push_back( c0 ); lambda0.push_back( a1*c0*c0 + c1 ); }else if (fabs(a1)<epsilon){ lambda0.push_back( c1 ); lambda1.push_back( a0*c1*c1 + c0 ); }else{ //find lamda0 by solving a deg 4 equation d0+d1*X+...+d4*X^4=0 double a[5]; a[0] = c1+a1*c0*c0; a[1] = -1; a[2] = 2*a1*a0*c0; a[3] = 0; a[4] = a1*a0*a0; //vector<double> solns=solve_poly(a,4); vector<double> solns=solve_lambda0(a0,a1,c0,c1,insist_on_speed_signs); for (unsigned i=0;i<solns.size();i++){ double lbda0=solns[i]; double lbda1=c0+a0*lbda0*lbda0; //is this solution pointing in the + direction at both ends? if (lbda0>=0. && lbda1>=0.){ lambda0.push_back( lbda0); lambda1.push_back( lbda1); } //is this solution pointing in the - direction at both ends? else if (lbda0<=0. && lbda1<=0. && insist_on_speed_signs<=0){ lambda0.push_back( lbda0); lambda1.push_back( lbda1); } //ok,this solution is pointing in the + and - directions. else if (insist_on_speed_signs<0){ lambda0.push_back( lbda0); lambda1.push_back( lbda1); } } } } for (unsigned i=0; i<lambda0.size(); i++){ Point V0 = lambda0[i]*dM0; Point V1 = lambda1[i]*dM1; D2<SBasis> cubic; for(unsigned dim=0;dim<2;dim++){ SBasis c(2, Linear()); c[0] = Linear(M0[dim],M1[dim]); c[1] = Linear( M0[dim]-M1[dim]+V0[dim], -M0[dim]+M1[dim]-V1[dim]); cubic[dim] = c; } #if 0 Piecewise<SBasis> k = curvature(result); double dM0_l = dM0.length(); double dM1_l = dM1.length(); g_warning("Target radii: %f, %f", dM0_l*dM0_l*dM0_l/d2M0xdM0,dM1_l*dM1_l*dM1_l/d2M1xdM1); g_warning("Obtained radii: %f, %f",1/k.valueAt(0),1/k.valueAt(1)); #endif result.push_back(cubic); } return(result); } std::vector<D2<SBasis> > Geom::cubics_fitting_curvature(Point const &M0, Point const &M1, Point const &dM0, Point const &dM1, Point const &d2M0, Point const &d2M1, int insist_on_speed_signs, double epsilon){ double d2M0xdM0 = cross(d2M0,dM0); double d2M1xdM1 = cross(d2M1,dM1); return cubics_fitting_curvature(M0,M1,dM0,dM1,d2M0xdM0,d2M1xdM1,insist_on_speed_signs,epsilon); } std::vector<D2<SBasis> > Geom::cubics_with_prescribed_curvature(Point const &M0, Point const &M1, Point const &dM0, Point const &dM1, double k0, double k1, int insist_on_speed_signs, double epsilon){ double length; length = dM0.length(); double d2M0xdM0 = k0*length*length*length; length = dM1.length(); double d2M1xdM1 = k1*length*length*length; return cubics_fitting_curvature(M0,M1,dM0,dM1,d2M0xdM0,d2M1xdM1,insist_on_speed_signs,epsilon); } /** * \brief returns all the parameter values of A whose tangent passes through P. */ std::vector<double> find_tangents(Point P, D2<SBasis> const &A) { SBasis crs (cross(A - P, derivative(A))); crs = shift(crs*Linear(-1, 0)*Linear(-1, 0), -2); // We know that there is a double root at t=0 so we divide out t^2 // JFB points out that this is equivalent to (t-1)^2 followed by a divide by s^2 (shift) return roots(crs); } //}; // namespace /* Local Variables: mode:c++ c-file-style:"stroustrup" c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) indent-tabs-mode:nil fill-column:99 End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :
Huluzai/DoonSketch
inkscape-0.48.5/src/2geom/sbasis-geometric.cpp
C++
gpl-2.0
25,700
/*************************************************************************** qgsadvanceddigitizingdockwidget.h - dock for CAD tools ---------------------- begin : October 2014 copyright : (C) Denis Rouzaud email : denis.rouzaud@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. * * * ***************************************************************************/ #ifndef QGSADVANCEDDIGITIZINGDOCK #define QGSADVANCEDDIGITIZINGDOCK #include "qgsdockwidget.h" #include "qgsmapmouseevent.h" #include "qgsmessagebaritem.h" #include <ui_qgsadvanceddigitizingdockwidgetbase.h> class QgsAdvancedDigitizingCanvasItem; class QgsMapCanvas; class QgsMapTool; class QgsMapToolAdvancedDigitizing; class QgsPoint; // tolerances for soft constraints (last values, and common angles) // for angles, both tolerance in pixels and degrees are used for better performance static const double SoftConstraintTolerancePixel = 15; static const double SoftConstraintToleranceDegrees = 10; /** * @brief The QgsAdvancedDigitizingDockWidget class is a dockable widget * used to handle the CAD tools on top of a selection of map tools. * It handles both the UI and the constraints. Constraints are applied * by implemeting filters called from QgsMapToolAdvancedDigitizing. */ class GUI_EXPORT QgsAdvancedDigitizingDockWidget : public QgsDockWidget, private Ui::QgsAdvancedDigitizingDockWidgetBase { Q_OBJECT Q_FLAGS( CadCapacities ) public: /** * The CadCapacity enum defines the possible constraints to be set * depending on the number of points in the CAD point list (the list of points * currently digitized) */ enum CadCapacity { AbsoluteAngle = 1, //!< Azimuth RelativeAngle = 2, //!< also for parallel and perpendicular RelativeCoordinates = 4, //!< this corresponds to distance and relative coordinates }; Q_DECLARE_FLAGS( CadCapacities, CadCapacity ) /** * Additional constraints which can be enabled */ enum AdditionalConstraint { NoConstraint, //!< No additional constraint Perpendicular, //!< Perpendicular Parallel //!< Parallel }; /** * @brief The CadConstraint is an abstract class for all basic constraints (angle/distance/x/y). * It contains all values (locked, value, relative) and pointers to corresponding widgets. * @note Relative is not mandatory since it is not used for distance. */ class GUI_EXPORT CadConstraint { public: /** * The lock mode */ enum LockMode { NoLock, SoftLock, HardLock }; /** Constructor for CadConstraint. * @param lineEdit associated line edit for constraint value * @param lockerButton associated button for locking constraint * @param relativeButton optional button for toggling relative constraint mode * @param repeatingLockButton optional button for toggling repeating lock mode */ CadConstraint( QLineEdit* lineEdit, QToolButton* lockerButton, QToolButton* relativeButton = nullptr, QToolButton* repeatingLockButton = nullptr ) : mLineEdit( lineEdit ) , mLockerButton( lockerButton ) , mRelativeButton( relativeButton ) , mRepeatingLockButton( repeatingLockButton ) , mLockMode( NoLock ) , mRepeatingLock( false ) , mRelative( false ) , mValue( 0.0 ) {} /** * The current lock mode of this constraint * @return Lock mode */ LockMode lockMode() const { return mLockMode; } /** * Is any kind of lock mode enabled */ bool isLocked() const { return mLockMode != NoLock; } /** Returns true if a repeating lock is set for the constraint. Repeating locks are not * automatically cleared after a new point is added. * @note added in QGIS 2.16 * @see setRepeatingLock() */ bool isRepeatingLock() const { return mRepeatingLock; } /** * Is the constraint in relative mode */ bool relative() const { return mRelative; } /** * The value of the constraint */ double value() const { return mValue; } /** * The line edit that manages the value of the constraint */ QLineEdit* lineEdit() const { return mLineEdit; } /** * Set the lock mode */ void setLockMode( LockMode mode ); /** Sets whether a repeating lock is set for the constraint. Repeating locks are not * automatically cleared after a new point is added. * @param repeating set to true to set the lock to repeat automatically * @note added in QGIS 2.16 * @see isRepeatingLock() */ void setRepeatingLock( bool repeating ); /** * Set if the constraint should be treated relative */ void setRelative( bool relative ); /** * Set the value of the constraint * @param value new value for constraint * @param updateWidget set to false to prevent automatically updating the associated widget's value */ void setValue( double value, bool updateWidget = true ); /** * Toggle lock mode */ void toggleLocked(); /** * Toggle relative mode */ void toggleRelative(); private: QLineEdit* mLineEdit; QToolButton* mLockerButton; QToolButton* mRelativeButton; QToolButton* mRepeatingLockButton; LockMode mLockMode; bool mRepeatingLock; bool mRelative; double mValue; }; //! performs the intersection of a circle and a line //! @note from the two solutions, the intersection will be set to the closest point static bool lineCircleIntersection( const QgsPoint& center, const double radius, const QList<QgsPoint>& segment, QgsPoint& intersection ); /** * Create an advanced digitizing dock widget * @param canvas The map canvas on which the widget operates * @param parent The parent */ explicit QgsAdvancedDigitizingDockWidget( QgsMapCanvas* canvas, QWidget *parent = nullptr ); /** * Disables the CAD tools when hiding the dock */ void hideEvent( QHideEvent* ) override; /** * Will react on a canvas press event * * @param e A mouse event (may be modified) * @return If the event is hidden (construction mode hides events from the maptool) */ bool canvasPressEvent( QgsMapMouseEvent* e ); /** * Will react on a canvas release event * * @param e A mouse event (may be modified) * @param captureSegment Capture segments? * @return If the event is hidden (construction mode hides events from the maptool) */ bool canvasReleaseEvent( QgsMapMouseEvent* e , bool captureSegment ); /** * Will react on a canvas move event * * @param e A mouse event (may be modified) * @return If the event is hidden (construction mode hides events from the maptool) */ bool canvasMoveEvent( QgsMapMouseEvent* e ); /** * Filter key events to e.g. toggle construction mode or adapt constraints * * @param e A mouse event (may be modified) * @return If the event is hidden (construction mode hides events from the maptool) */ bool canvasKeyPressEventFilter( QKeyEvent *e ); //! apply the CAD constraints. The will modify the position of the map event in map coordinates by applying the CAD constraints. //! @return false if no solution was found (invalid constraints) virtual bool applyConstraints( QgsMapMouseEvent* e ); /** * Clear any cached previous clicks and helper lines */ void clear(); /** * The snapping mode * @return Snapping mode */ QgsMapMouseEvent::SnappingMode snappingMode() { return mSnappingMode; } //! key press event on the dock void keyPressEvent( QKeyEvent* e ) override; //! determines if CAD tools are enabled or if map tools behaves "nomally" bool cadEnabled() const { return mCadEnabled; } //! construction mode is used to draw intermediate points. These points won't be given any further (i.e. to the map tools) bool constructionMode() const { return mConstructionMode; } //! Additional constraints are used to place perpendicular/parallel segments to snapped segments on the canvas AdditionalConstraint additionalConstraint() const { return mAdditionalConstraint; } //! Constraint on the angle const CadConstraint* constraintAngle() const { return mAngleConstraint.data(); } //! Constraint on the distance const CadConstraint* constraintDistance() const { return mDistanceConstraint.data(); } //! Constraint on the X coordinate const CadConstraint* constraintX() const { return mXConstraint.data(); } //! Constraint on the Y coordinate const CadConstraint* constraintY() const { return mYConstraint.data(); } //! Constraint on a common angle bool commonAngleConstraint() const { return mCommonAngleConstraint; } /** * The last point. * Helper for the CAD point list. The CAD point list is the list of points * currently digitized. It contains both "normal" points and intermediate points (construction mode). */ QgsPoint currentPoint( bool* exists = nullptr ) const; /** * The previous point. * Helper for the CAD point list. The CAD point list is the list of points * currently digitized. It contains both "normal" points and intermediate points (construction mode). */ QgsPoint previousPoint( bool* exists = nullptr ) const; /** * The penultimate point. * Helper for the CAD point list. The CAD point list is the list of points * currently digitized. It contains both "normal" points and intermediate points (construction mode). */ QgsPoint penultimatePoint( bool* exists = nullptr ) const; /** * The number of points in the CAD point helper list */ inline int pointsCount() const { return mCadPointList.count(); } /** * Is it snapped to a vertex */ inline bool snappedToVertex() const { return mSnappedToVertex; } /** * Snapped to a segment */ const QList<QgsPoint>& snappedSegment() const { return mSnappedSegment; } //! return the action used to enable/disable the tools QAction* enableAction() { return mEnableAction; } /** * Enables the tool (call this when an appropriate map tool is set and in the condition to make use of * cad digitizing) * Normally done automatically from QgsMapToolAdvancedDigitizing::activate() but may need to be fine tuned * if the map tool depends on preconditions like a feature selection. */ void enable(); /** * Disable the widget. Normally done automatically from QgsMapToolAdvancedDigitizing::deactivate(). */ void disable(); signals: /** * Push a warning * * @param message An informative message */ void pushWarning( const QString& message ); /** * Remove any previously emitted warnings (if any) */ void popWarning(); /** * Sometimes a constraint may change the current point out of a mouse event. This happens normally * when a constraint is toggled. * * @param point The last known digitizing point. Can be used to emulate a mouse event. */ void pointChanged( const QgsPoint& point ); private slots: //! set the additional constraint by clicking on the perpendicular/parallel buttons void addtionalConstraintClicked( bool activated ); //! lock/unlock a constraint and set its value void lockConstraint( bool activate = true ); //! Called when user has manually altered a constraint value. Any entered expressions will //! be left intact void constraintTextEdited( const QString& textValue ); //! Called when a constraint input widget has lost focus. Any entered expressions //! will be converted to their calculated value void constraintFocusOut(); //! unlock all constraints //! @param releaseRepeatingLocks set to false to preserve the lock for any constraints set to repeating lock mode void releaseLocks( bool releaseRepeatingLocks = true ); //! set the relative properties of constraints void setConstraintRelative( bool activate ); //! Set the repeating lock property of constraints void setConstraintRepeatingLock( bool activate ); //! activate/deactivate tools. It is called when tools are activated manually (from the GUI) //! it will call setCadEnabled to properly update the UI. void activateCad( bool enabled ); //! enable/disable construction mode (events are not forwarded to the map tool) void setConstructionMode( bool enabled ); //! settings button triggered void settingsButtonTriggered( QAction* action ); private: //! updates the UI depending on activation of the tools and clear points / release locks. void setCadEnabled( bool enabled ); /** * @brief updateCapacity updates the cad capacities depending on the point list and update the UI according to the capabilities. * @param updateUIwithoutChange if true, it will update the UI even if new capacities are not different from previous ones. */ void updateCapacity( bool updateUIwithoutChange = false ); //! defines the additional constraint to be used (no/parallel/perpendicular) void lockAdditionalConstraint( AdditionalConstraint constraint ); QList<QgsPoint> snapSegment( const QgsPointLocator::Match& snapMatch ); //! align to segment for additional constraint. //! If additional constraints are used, this will determine the angle to be locked depending on the snapped segment. bool alignToSegment( QgsMapMouseEvent* e, CadConstraint::LockMode lockMode = CadConstraint::HardLock ); //! add point to the CAD point list void addPoint( const QgsPoint& point ); //! update the current point in the CAD point list void updateCurrentPoint( const QgsPoint& point ); //! remove previous point in the CAD point list void removePreviousPoint(); //! remove all points from the CAD point list void clearPoints(); //! filters key press //! @note called by eventFilter (fitler on line edits), canvasKeyPressEvent (filter on map tool) and keyPressEvent (filter on dock) bool filterKeyPress( QKeyEvent* e ); //! event filter for line edits in the dock UI (angle/distance/x/y line edits) bool eventFilter( QObject *obj, QEvent *event ) override; //! trigger fake mouse move event to update map tool rubber band and/or show new constraints void triggerMouseMoveEvent(); //! Returns the constraint associated with an object CadConstraint* objectToConstraint( const QObject* obj ) const; //! Attempts to convert a user input value to double, either directly or via expression double parseUserInput( const QString& inputValue, bool& ok ) const; /** Updates a constraint value based on a text input. * @param constraint constraint to update * @param textValue user entered text value, may be an expression * @param convertExpression set to true to update widget contents to calculated expression value */ void updateConstraintValue( CadConstraint* constraint, const QString& textValue, bool convertExpression = false ); QgsMapCanvas* mMapCanvas; QgsAdvancedDigitizingCanvasItem* mCadPaintItem; CadCapacities mCapacities; bool mCurrentMapToolSupportsCad; // CAD properties //! is CAD currently enabled for current map tool bool mCadEnabled; bool mConstructionMode; QgsMapMouseEvent::SnappingMode mSnappingMode; // constraints QScopedPointer< CadConstraint > mAngleConstraint; QScopedPointer< CadConstraint > mDistanceConstraint; QScopedPointer< CadConstraint > mXConstraint; QScopedPointer< CadConstraint > mYConstraint; AdditionalConstraint mAdditionalConstraint; int mCommonAngleConstraint; // if 0: do not snap to common angles // point list and current snap point / segment QList<QgsPoint> mCadPointList; QList<QgsPoint> mSnappedSegment; bool mSnappedToVertex; bool mSessionActive; // error message QScopedPointer<QgsMessageBarItem> mErrorMessage; // UI QAction* mEnableAction; QMap< QAction*, int > mCommonAngleActions; // map the common angle actions with their angle values QMap< QAction*, QgsMapMouseEvent::SnappingMode > mSnappingActions; // map the snapping mode actions with their values }; Q_DECLARE_OPERATORS_FOR_FLAGS( QgsAdvancedDigitizingDockWidget::CadCapacities ) #endif // QGSADVANCEDDIGITIZINGDOCK_H
dhenrygithub/QGIS
src/gui/qgsadvanceddigitizingdockwidget.h
C
gpl-2.0
17,540
<?php /** * The template for displaying Comments. * * The area of the page that contains both current comments * and the comment form. The actual display of comments is * handled by a callback to skt_photo_session_comment() which is * located in the inc/template-tags.php file. * * @package SKT Photo Session */ /* * If the current post is protected by a password and * the visitor has not yet entered the password we will * return early without loading the comments. */ if ( post_password_required() ) return; ?> <div id="comments" class="comments-area"> <?php // You can start editing here -- including this comment! ?> <?php if ( have_comments() ) : ?> <h2 class="comments-title"> <?php printf( _nx( 'One thought on &ldquo;%2$s&rdquo;', '%1$s thoughts on &ldquo;%2$s&rdquo;', get_comments_number(), 'comments title', 'skt-photo-session' ), number_format_i18n( get_comments_number() ), '<span>' . get_the_title() . '</span>' ); ?> </h2> <?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?> <nav id="comment-nav-above" class="comment-navigation" role="navigation"> <h1 class="screen-reader-text"><?php _e( 'Comment navigation', 'skt-photo-session' ); ?></h1> <div class="nav-previous"><?php previous_comments_link( __( '&larr; Older Comments', 'skt-photo-session' ) ); ?></div> <div class="nav-next"><?php next_comments_link( __( 'Newer Comments &rarr;', 'skt-photo-session' ) ); ?></div> </nav><!-- #comment-nav-above --> <?php endif; // check for comment navigation ?> <ol class="comment-list"> <?php /* Loop through and list the comments. Tell wp_list_comments() * to use skt_photo_session_comment() to format the comments. * If you want to override this in a child theme, then you can * define skt_photo_session_comment() and that will be used instead. * See skt_photo_session_comment() in inc/template-tags.php for more. */ wp_list_comments( array( 'callback' => 'skt_photo_session_comment' ) ); ?> </ol><!-- .comment-list --> <?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?> <nav id="comment-nav-below" class="comment-navigation" role="navigation"> <h1 class="screen-reader-text"><?php _e( 'Comment navigation', 'skt-photo-session' ); ?></h1> <div class="nav-previous"><?php previous_comments_link( __( '&larr; Older Comments', 'skt-photo-session' ) ); ?></div> <div class="nav-next"><?php next_comments_link( __( 'Newer Comments &rarr;', 'skt-photo-session' ) ); ?></div> </nav><!-- #comment-nav-below --> <?php endif; // check for comment navigation ?> <?php endif; // have_comments() ?> <?php // If comments are closed and there are comments, let's leave a little note, shall we? if ( ! comments_open() && '0' != get_comments_number() && post_type_supports( get_post_type(), 'comments' ) ) : ?> <p class="no-comments"><?php _e( 'Comments are closed.', 'skt-photo-session' ); ?></p> <?php endif; ?> <?php comment_form(); ?> </div><!-- #comments -->
selinaross/JessesWebsite
wp-content/themes/skt-photo-session/comments.php
PHP
gpl-2.0
3,137
<?php /** * Googleapps helper functions * * @package Googleapps * @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU Public License version 2 * @author Jeff Tilson * @copyright THINK Global School 2010 - 2015 * @link http://www.thinkglobalschool.org/ * */ /** * Get account settings content */ function googleapps_get_page_content_settings_account() { $params['title'] = elgg_echo('googleapps:menu:google_sync_settings'); $user = elgg_get_logged_in_user_entity(); if ($user->google_connected == TRUE) { $vars = array( 'id' => 'google-auth-settings-form', 'forms' => 'google_auth_settings_form', ); $params['content'] = elgg_view_form('google/auth/settings', $vars, array('user' => $user)); $params['content'] .= elgg_view_form('google/auth/disconnect', array('class' => 'elgg-form-alt')); } else { $params['content'] = elgg_view_form('google/auth/connect'); } $params['layout'] = 'one_sidebar'; return $params; } /** * Get google docs listing content */ function googleapps_get_page_content_docs_list($container_guid = NULL) { elgg_load_js('elgg.googlefilepicker'); elgg_load_js('google-js-api'); elgg_load_js('google-doc-picker-client'); $params['filter_context'] = $container_guid ? 'mine' : 'all'; if ($container_guid) { $container = get_entity($container_guid); // Make sure container is a user or group, otherwise things will look weird if (!elgg_instanceof($container, 'user') && !elgg_instanceof($container, 'group')) { // Scram.. forward('googleapps/docs/all'); } if ($container != elgg_get_logged_in_user_entity() || elgg_instanceof($container, 'group')) { $params['filter_context'] = FALSE; } elgg_push_breadcrumb(elgg_echo('googleapps:googleshareddoc'), elgg_get_site_url() . 'googleapps/docs/all'); elgg_push_breadcrumb($container->name); $content = elgg_list_entities(array( 'type' => 'object', 'subtype' => 'shared_doc', 'container_guid' => $container_guid, 'full_view' => FALSE )); $params['title'] = elgg_echo('googleapps:label:user_docs', array($container->name)); } else { elgg_push_breadcrumb(elgg_echo('googleapps:googleshareddoc'), elgg_get_site_url() . 'googleapps/docs/all'); $content = elgg_list_entities(array( 'type' => 'object', 'subtype' => 'shared_doc', 'full_view' => FALSE )); $params['title'] = elgg_echo('googleapps:menu:allshareddocs'); } $owner = elgg_get_page_owner_entity(); if (!$owner) { $owner = elgg_get_logged_in_user_entity(); } // Only allow creating google docs if google connected and allowed to write to container if ($owner && $owner->canWriteToContainer() && elgg_get_logged_in_user_entity()->google_connected) { $guid = $owner->getGUID(); elgg_register_menu_item('title', array( 'name' => 'googleapps_docs_add', 'href' => "googleapps/docs/add/{$guid}", 'text' => elgg_echo("googleapps/docs:add"), 'link_class' => 'elgg-button elgg-button-action google-doc-picker', )); } // If theres no content, display a nice message if (!$content) { $content = elgg_view('googleapps/noresults'); } $params['context'] = 'googleapps/docs'; $params['content'] = $content; return $params; } /** * Get friends docs */ function googleapps_get_page_content_docs_friends($user_guid) { $user = get_entity($user_guid); elgg_push_breadcrumb(elgg_echo('googleapps:googleshareddoc'), elgg_get_site_url() . 'googleapps/docs/all'); elgg_push_breadcrumb($user->name, elgg_get_site_url() . 'googleapps/docs/owner/' . $user->username); elgg_push_breadcrumb(elgg_echo('friends')); if (!$friends = get_user_friends($user_guid, ELGG_ENTITIES_ANY_VALUE, 0)) { $content .= elgg_echo('friends:none:you'); } else { $options = array( 'type' => 'object', 'subtype' => 'shared_doc', 'full_view' => FALSE, ); foreach ($friends as $friend) { $options['container_guids'][] = $friend->getGUID(); } $params['title'] = elgg_echo('googleapps:menu:friendsshareddocs'); $list = elgg_list_entities($options); if (!$list) { $content .= elgg_view('googleapps/noresults'); } else { $content .= $list; } } $params['filter_context'] = 'friends'; $params['context'] = 'googleapps/docs'; $params['content'] = $content; return $params; } /** * Get google docs share/edit content * * @param int $guid Document guid (for editing) * @return array */ function googleapps_get_page_content_docs_share($guid = null) { $google_doc = get_entity($guid); elgg_push_breadcrumb(elgg_echo('googleapps:googleshareddoc'), elgg_get_site_url() . 'googleapps/docs/all'); if (elgg_instanceof($google_doc, 'object', 'shared_doc')) { elgg_push_breadcrumb($google_doc->title); elgg_push_breadcrumb(elgg_echo('googleapps:docs:edit')); $body_vars = google_doc_prepare_form_vars($google_doc); $title = elgg_echo('googleapps:label:editdoc', array($google_doc->title)); } else { elgg_push_breadcrumb(elgg_echo('googleapps/docs:add')); $body_vars = array(); $title = elgg_echo('googleapps:label:google_docs'); } $params = array( 'filter' => '', ); $params['title'] = $title; // Form vars $vars = array(); $vars['id'] = 'google-docs-share-form'; $vars['name'] = 'google_docs_share_form'; // View share form $params['content'] = elgg_view_form('google/docs/share', $vars, $body_vars); return $params; } /** * Get google sites/wiki content */ function googleapps_get_page_content_wikis_list($container_guid = NULL) { elgg_push_breadcrumb(elgg_echo('googleapps:menu:wikis'), elgg_get_site_url() . 'googleapps/wikis/all'); $params['context'] = 'googleapps/wikis'; $params['title'] = elgg_echo('googleapps:menu:wikis'); $params['filter_context'] = $container_guid ? 'mine' : 'all'; $db_prefix = elgg_get_config('dbprefix'); $order = sanitize_string(get_input('order', 'ASC')); $order_by = sanitize_string(get_input('by', 'alpha')); // Default options (for 'ALL') $options = array( 'type' => 'object', 'subtype' => 'site', 'full_view' => FALSE, 'limit' => 10, ); if ($order_by == 'updated') { $options['order_by_metadata'] = array('name' => 'modified', 'as' => 'int', 'direction' => $order); $options['reverse_order_by'] = TRUE; $list = elgg_list_entities_from_metadata($options); } else { $options['joins'] = array("JOIN {$db_prefix}objects_entity oe on e.guid = oe.guid"); $options['order_by'] = "oe.title {$order}"; $list = elgg_list_entities($options); } $content = elgg_view('googleapps/wiki_sort'); if (!$list) { $content .= elgg_view('googleapps/noresults'); } else { $content .= $list; } $params['content'] = $content; $params['sidebar'] = elgg_view('googleapps/featured_site_sidebar'); $domain = elgg_get_plugin_setting('google_api_domain', 'googleapps'); $new_url = 'https://sites.google.com/a/' . $domain . '/sites/system/app/pages/meta/dashboard/create-new-site'; // Show create wiki button if (elgg_is_logged_in()) { elgg_register_menu_item('title', array( 'name' => 'add', 'href' => $new_url, 'text' => elgg_echo('googleapps:menu:create_new_wiki'), 'link_class' => 'elgg-button elgg-button-action', )); } $params['filter'] = ' '; return $params; } /** * Pull together google doc variables for the edit form * * @param ElggObject $google_doc * @return array */ function google_doc_prepare_form_vars($google_doc = NULL) { // input names => defaults $values = array( 'title' => NULL, 'description' => NULL, 'tags' => NULL, 'container_guid' => NULL, 'guid' => NULL, ); if ($google_doc) { foreach (array_keys($values) as $field) { if (isset($google_doc->$field)) { $values[$field] = $google_doc->$field; } } } if (elgg_is_sticky_form('google-docs-edit-form')) { $sticky_values = elgg_get_sticky_values('google-docs-edit-form'); foreach ($sticky_values as $key => $value) { $values[$key] = $value; } } elgg_clear_sticky_form('google-docs-edit-form'); return $values; } /** * Prepare form vars for google calendars * * @param mixed $entity * @return arary */ function google_calendars_prepare_form_vars($calendar = null) { // input names => defaults $values = array( 'title' => '', 'google_cal_feed' => '', 'text_color' => '', 'background_color' => '', 'access_id' => ACCESS_DEFAULT, 'guid' => '' ); if (elgg_is_sticky_form('google-calendar-save')) { foreach (array_keys($values) as $field) { $values[$field] = elgg_get_sticky_value('google-calendar-save', $field); } } elgg_clear_sticky_form('google-calendar-save'); if (!$calendar) { return $values; } foreach (array_keys($values) as $field) { if (isset($calendar->$field)) { $values[$field] = $calendar->$field; } } $values['entity'] = $calendar; return $values; } /** * Retrieve and parse allowed subdomains from plugin settings * * @return array | bool */ function googleapps_get_allowed_subdomains() { $subdomain_setting = elgg_get_plugin_setting('googleapps_subdomains', 'googleapps'); $subdomains = preg_split('/[\.,\s]/', $subdomain_setting, -1, PREG_SPLIT_NO_EMPTY); if (empty($subdomains)) { return FALSE; } else { return $subdomains; } } /** * Generate google client * * @return Google_Client */ function googleapps_get_client() { elgg_load_library('gapc:Client'); // Main client elgg_load_library('gapc:Plus'); // Plus // Get client id/secret from plugin settings $client_id = elgg_get_plugin_setting('google_api_client_id', 'googleapps'); $client_secret = elgg_get_plugin_setting('google_api_client_secret', 'googleapps'); $redirect_uri = elgg_get_site_url() . "googleapps/auth/callback"; $client = new Google_Client(); $client->setClientId($client_id); $client->setClientSecret($client_secret); $client->setRedirectUri($redirect_uri); $client->setScopes(array( 'email', 'profile', 'https://sites.google.com/feeds/', 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/calendar.readonly', 'https://www.googleapis.com/auth/calendar' )); $client->setAccessType('offline'); $client->setApplicationName(elgg_get_plugin_setting('google_domain_label', 'googleapps')); return $client; } /** * Generate a google service account client */ function googleapps_get_service_client($scopes = array()) { elgg_load_library('gapc:Client'); $plugin = elgg_get_plugin_from_id('googleapps'); $client = new Google_Client(); $client->setApplicationName(elgg_get_plugin_setting('google_domain_label', 'googleapps')); // Get auth/key info from plugin settings $key_location = elgg_get_plugin_setting('google_service_client_key', 'googleapps'); $key_password = elgg_get_plugin_setting('google_service_client_key_password', 'googleapps'); $service_account = elgg_get_plugin_setting('google_service_client_address', 'googleapps'); $impersonate = elgg_get_plugin_setting('google_service_client_key_impersonate', 'googleapps'); $key = file_get_contents($key_location); // Get credentials $credentials = new Google_Auth_AssertionCredentials( $service_account, $scopes, $key, $key_password, 'http://oauth.net/grant_type/jwt/1.0/bearer', $impersonate ); $client->setAssertionCredentials($credentials); if($client->getAuth()->isAccessTokenExpired()) { $client->getAuth()->refreshTokenWithAssertion($credentials); } return $client; } /** * Delete all site entities (debug) */ function googleapps_delete_all_site_entities() { $site_entities = elgg_get_entities(array( 'type' => 'object', 'subtype' => 'site', 'limit' => 0 )); foreach($site_entities as $site_entity) { $site_entity->delete(); } return; } /** * Change the google drive file permissions based on chosen elgg permissions * * @param object $client * @param string $doc_id Document id * @param string $access public | domain * @param array $optParams optional params to send along with insert * @return bool */ function googleapps_update_file_permissions($client, $doc_id, $access, $optParams = array()) { if (empty($doc_id) || !$doc_id) { return FALSE; } elgg_load_library('gapc:Drive'); // Load drive lib $service = new Google_Service_Drive($client); // May insert multiple permissions $permissions = array(); // Set new permission based on access requested if ($access == "domain") { $permission = new Google_Service_Drive_Permission(); $permission->setRole('reader'); $domain = elgg_get_plugin_setting('google_api_domain', 'googleapps'); $permission->setType('domain'); $permission->setDomain($domain); $permission->setValue($domain); $permissions[] = $permission; } else if ($access == 'public') { $permission = new Google_Service_Drive_Permission(); $permission->setRole('reader'); $permission->setType('anyone'); $permission->setValue('anyone'); $permissions[] = $permission; } else if (is_array($access)) { // Array of ElggUsers foreach ($access as $user) { $permission = new Google_Service_Drive_Permission(); $permission->setRole('reader'); $permission->setAdditionalRoles(["commenter"]); $permission->setType('user'); $permission->setValue($user->email); $permissions[] = $permission; } } try { $success = TRUE; // Handle multiple permissions foreach ($permissions as $permission) { $success &= $service->permissions->insert($doc_id, $permission, $optParams); } return $success; } catch (Exception $e) { //var_dump($e); return FALSE; } } /** * Get a single google drive file from supplied ID * * @param object $client * @param string $id * @return Google_Service_Drive_DriveFile */ function googleapps_get_file_from_id($client, $id) { if (empty($id) || !$id) { return FALSE; } elgg_load_library('gapc:Drive'); // Load drive lib $service = new Google_Service_Drive($client); $file = $service->files->get($id); return $file; } /** * Get permissions for a single google drive file from supplied ID * * @param object $client * @param string $id * @return array Google_Service_Drive_Permission */ function googleapps_get_file_permissions_from_id($client, $id) { if (empty($id) || !$id) { return FALSE; } elgg_load_library('gapc:Drive'); // Load drive lib $service = new Google_Service_Drive($client); $permissions = $service->permissions->listPermissions($id)->getItems(); return $permissions; } /** * Create/save a shared google document * * @param Google_Service_Drive_DriveFile $document The google drive document * @param array $params Elgg object params array: * * description => null|string Document description * * tags => null|array Document tags * * access_id => null|INT Document access level * * container_guid => null|INT Container guid for the document * * entity_guid => null|INT Supply this to update an existing entity * * @return bool */ function googleapps_save_shared_document($document, $params = array()) { // Check for valid drive file if (!($document instanceof Google_Service_Drive_DriveFile)) { register_error(elgg_echo('googleapps:error:invaliddoc')); return FALSE; } // Supply some defaults $defaults = array( 'access_id' => ACCESS_LOGGED_IN, 'container_guid' => elgg_get_logged_in_user_guid(), 'entity_guid' => FALSE ); $params = array_merge($defaults, $params); // Check if we were supplied with an entity_guid if ($params['entity_guid']) { // Got one, check if it's a valid entity $shared_doc = get_entity($params['entity_guid']); if (!elgg_instanceof($shared_doc, 'object', 'shared_doc')) { register_error(elgg_echo('googleapps:error:invaliddoc')); return FALSE; } } else { // New object $shared_doc = new ElggObject(); $shared_doc->subtype = 'shared_doc'; } // Set document metadata from drive object $shared_doc->title = $document->getTitle(); $shared_doc->res_id = $document->getId(); $shared_doc->updated = strtotime($document->getModifiedDate()); // CHECK ME $shared_doc->href = $document->getAlternateLink(); $shared_doc->icon = $document->getIconLink(); $shared_doc->description = $params['description']; $shared_doc->access_id = $params['access_id']; $shared_doc->container_guid = $params['container_guid']; $shared_doc->tags = string_to_tag_array($params['tags']); if (!$shared_doc->save()) { register_error(elgg_echo('googleapps:error:share_doc')); exit; } if (!$params['entity_guid']) { // Add to river elgg_create_river_item(array( 'view' => 'river/object/shared_doc/create', 'action_type' => 'create', 'subject_guid' => elgg_get_logged_in_user_guid(), 'object_guid' => $shared_doc->guid )); } return TRUE; } /** * Return given user's access tokens (default is logged in user) * * @param ElggUser $user * @return string json_encode'd array of user access tokens */ function googleapps_get_user_access_tokens($user = FALSE) { if (!elgg_instanceof($user, 'user')) { $user = elgg_get_logged_in_user_entity(); } return json_encode(array( 'access_token' => $user->google_access_token, 'refresh_token' => $user->google_refresh_token )); } /** * Process Google Sites * - Creates new local entities * - Deletes local entities not found/deleted remotley * * @return array|false */ function googleapps_process_sites() { // Don't do anything if sites are disabled if (elgg_get_plugin_setting('enable_google_sites', 'googleapps') == 'no') { return FALSE; } set_time_limit(0); // Long timeout, just in case $log .= "Processing Google Sites\n"; $log .= "-----------------------\n"; // Get service client $client = googleapps_get_service_client(array( 'https://sites.google.com/feeds/' )); if ($client) { $domain = elgg_get_plugin_setting('google_api_domain', 'googleapps'); $base_feed = "https://sites.google.com/feeds/site/{$domain}"; $feed_params = array( 'alt' => 'json', 'include-all-sites' => 'true', 'max-results' => 500, ); $feed_url = $base_feed . '?' . implode_assoc('=', '&', $feed_params); $log .= "Request: {$feed_url}\n"; // Get sites feed $request = new Google_Http_Request($feed_url, 'GET'); $response = $client->getAuth()->authenticatedRequest($request); $response = json_decode($response->getResponseBody(), TRUE); if ($response && is_array($response) && count($response) > 0) { $log .= "\nSuccess..\n\n"; // Get exising elgg site entities $site_entities = elgg_get_entities(array( 'type' => 'object', 'subtype' => 'site', 'limit' => 0 )); // Elgg site guid, for owner/container guid's $site_guid = elgg_get_site_entity()->guid; if (!$site_entities) { $site_count = 0; } else { $site_count = count($site_entities); } $log .= "Found {$site_count} local site(s)\n"; // Array to compare local site id's $local_site_ids = array(); // Array to compate remote site id's $remote_site_ids = array(); // Build an array of remote site id's foreach ($response['feed']['entry'] as $site) { $site_id = $site['id']['$t']; $remote_site_ids[] = $site_id; } // Deleted count $sites_deleted = 0; // Process local sites foreach ($site_entities as $site) { $log .= "\n[{$site->title}]\n"; $log .= "ID: {$site->site_id}\n"; $log .= "URL: {$site->url}\n"; $local_site_ids[] = $site->site_id; // Make sure site entity is owned by the elgg site, not a specific user if ($site->container_guid != $site_guid) { $site->container_guid = $site_guid; $site->owner_guid = $site_guid; $site->save(); $log .= "Updated owner/container guid: {$site_guid}\n"; } // Remove deleted/unavailable local sites if (!in_array($site->site_id, $remote_site_ids)) { $log .= "Site not found remotely, will be deleted.\n"; $site->delete(); $sites_deleted++; } } // Process all remote sites $log .= "\nFound " . count($response['feed']['entry']) . " remote site(s)\n"; $log .= "\nRemote list:\n------------\n"; // Array to hold new site $new_sites = array(); // Process new sites foreach ($response['feed']['entry'] as $site) { $site_title = $site['title']['$t']; $site_id = $site['id']['$t']; $log .= "\n[{$site_title}]\n"; $log .= "ID: {$site_id}\n"; // Locate site URL and ACL feed url foreach($site['link'] as $link) { if ($link['rel'] == 'alternate') { $site_url = $link['href']; } else if ($link['rel'] == 'http://schemas.google.com/acl/2007#accessControlList') { $acl_url = $link['href']; } } // Build ACL feed request $acl_feed_params = array( 'alt' => 'json' ); $acl_feed_url = $acl_url . '?' . implode_assoc('=', '&', $acl_feed_params); // Get ACL feed $request = new Google_Http_Request($acl_feed_url, 'GET'); $response = $client->getAuth()->authenticatedRequest($request); $response = json_decode($response->getResponseBody(), TRUE); // Build an array of owner emails $site_owners = array(); foreach ($response['feed']['entry'] as $entry) { if ($entry['gAcl$role']['value'] == 'owner' && $entry['gAcl$scope']['type'] == 'user') { $site_owners[] = $entry['gAcl$scope']['value']; } } // Get activity feed (just replace feed location from the acl feed url) $activity_url = preg_replace('!(.*)feeds/acl/site/(.*)!', '$1feeds/activity/$2', $acl_feed_url); // Get activity feed $request = new Google_Http_Request($activity_url, 'GET'); $response = $client->getAuth()->authenticatedRequest($request); $response = json_decode($response->getResponseBody(), TRUE); // See if there is any site activity, if so grab the latest timestamp $site_updated = FALSE; foreach ($response['feed']['entry'] as $entry) { $site_updated = strtotime($entry['updated']['$t']); break; } // If there was no site activity, use the main site feed updated timestamp if (!$site_updated) { $site_updated = strtotime($site['updated']['$t']); } $log .= "URL: {$site_url}\n"; if (!in_array($site_id, $local_site_ids)) { $new_sites[$site_title] = $site_id; // Create new site $new_site = new ElggObject(); $new_site->owner_guid = $site_guid; $new_site->container_guid = $site_guid; $new_site->site_id = $site_id; $new_site->title = $site_title; $new_site->subtype = "site"; $new_site->url = $site_url; $new_site->modified = $site_updated; $new_site->remote_owners = $site_owners; $new_site->access_id = ACCESS_LOGGED_IN; // Default access, admin controlled //$new_site->site_access_id = ACCESS_PRIVATE ; // for site $new_site->save(); $log .= "New site! ({$new_site->guid})\n"; } else { $log .= "Local site exists!\n"; // Update local site info $remote_site = array( 'modified' => $site_updated, 'owners' => $site_owners, 'url' => $site_url, 'title' => $site_title, 'site_id' => $site_id ); googleapps_update_local_site_info($remote_site); } } // New count $sites_created = count($new_sites); $log .= "\n\nCreated {$sites_created} local site(s)\n"; $log .= "Deleted {$sites_deleted} local site(s)\n"; // Get exising elgg site entities again $site_entities = elgg_get_entities(array( 'type' => 'object', 'subtype' => 'site', 'limit' => 0 )); } else { $log .= "\n" . $result; $log .= "\nNo sites found\n"; } } else { $log .= "Error creating client!\n"; return FALSE; } if (elgg_in_context('googleapps_sites_log')) { echo "<pre>"; echo $log; echo "</pre>"; } return array( 'response_list'=>$response, 'site_entities'=>$site_entities, 'all_site_entities'=>$site_entities // @TODO phase this out ); } /** * Process Google Sites Activity * - Creates new activity items for sites (group connected) * * @return array|false */ function googleapps_process_sites_activity() { // Don't do anything if sites are disabled if (elgg_get_plugin_setting('enable_google_sites', 'googleapps') == 'no') { return FALSE; } set_time_limit(0); // Long timeout, just in case $log .= "Processing Google Sites Activity\n"; $log .= "--------------------------------\n"; /** GET LOCAL WIKIS THAT ARE CONNECTED TO A GROUP **/ $options = array( 'type' => 'object', 'subtype' => 'site', 'limit' => 0, ); $relationship = GOOGLEAPPS_GROUP_WIKI_RELATIONSHIP; $dbprefix = elgg_get_config('dbprefix'); // Where clause to ignore wikis that already have a relationship with another group $options['wheres'] = "EXISTS ( SELECT 1 FROM {$dbprefix}entity_relationships r2 WHERE r2.guid_one = e.guid AND r2.relationship = '{$relationship}')"; // Get a count $options['count'] = TRUE; $count = elgg_get_entities($options); if ($count >= 1) { $log .= "Found {$count} connected site(s).\n"; // Grab sites as a batch unset($options['count']); $sites = new ElggBatch('elgg_get_entities', $options); // Array to contain site->group relationship $sites_groups = array(); foreach ($sites as $site) { $log .= "\n[{$site->title}]\n"; $log .= "ID: {$site->site_id}\n"; $log .= "URL: {$site->url}\n"; // Get the connected group $options = array( 'type' => 'group', 'limit' => 1, // Should only be connected to one group 'full_view' => FALSE, 'relationship' => GOOGLEAPPS_GROUP_WIKI_RELATIONSHIP, 'relationship_guid' => $site->guid, 'inverse_relationship' => FALSE, ); $connected_groups = elgg_get_entities_from_relationship($options); $log .= "GROUP: "; if (count($connected_groups)) { // Store site/group $sites_groups[] = array('site' => $site, 'group' => $connected_groups[0]); $log .= $connected_groups[0]->name . " (" . $connected_groups[0]->guid . ")\n"; $log .= "Last Activity: {$site->last_activity_time}\n"; } else { $log .= "Couldn't find group! Not processing!\n"; } } // Get service client $client = googleapps_get_service_client(array( 'https://sites.google.com/feeds/' )); if ($client) { $domain = elgg_get_plugin_setting('google_api_domain', 'googleapps'); // Elgg site guid, for owner/container guid's $site_guid = elgg_get_site_entity()->guid; // Loop over our connected sites foreach ($sites_groups as $site_group) { $site = $site_group['site']; // Site entity $group = $site_group['group']; // Group entity // Create feed url $activity_feed = preg_replace('!(.*)feeds/site/(.*)!', '$1feeds/activity/$2', $site->site_id); $activity_feed_params = array( 'alt' => 'json', 'max-results' => 500, ); $activity_feed_url = $activity_feed . '?' . implode_assoc('=', '&', $activity_feed_params); $log .= "\nProcessing [{$site->title}]...\n\n Request: {$activity_feed_url}\n\n"; // Skip sites that have been set back to private if ($site->access_id == ACCESS_PRIVATE) { $log .= " Site's access is PRIVATE, skipping.\n"; continue; } // Get activity feed $request = new Google_Http_Request($activity_feed_url, 'GET'); $response = $client->getAuth()->authenticatedRequest($request); $response = json_decode($response->getResponseBody(), TRUE); $last_activity_time = $site->last_activity_time; $site_new_activity_count = 0; // Hold each activity items updated timestamp (to store later) $activity_times = array(); // Title for activity $title = "Changes on {$site->title} site"; // Loop over activity entries foreach ($response['feed']['entry'] as $entry) { $activity_time = strtotime($entry['updated']['$t']); if ($last_activity_time < $activity_time) { // Get activity info $summary = $entry['summary']['$t']; // Parse out summary link preg_match_all('~<a\s+.*?</a>~is',$summary,$anchors); $summary_link = $anchors[0][0]; $author_email = $entry['author'][0]['email']['$t']; $author_name = $entry['author'][0]['name']['$t']; // Store activity timestamps $activity_times[] = $activity_time; if (empty($author_email)) { $author_email = NULL; $author_output = "(unknown)"; } else { // Try to find elgg user $users = get_user_by_email($author_email); if (count($users) >= 1 && elgg_instanceof($users[0], 'user')) { $local_user = $users[0]; $author_output = $local_user->username; } else { $author_output = $author_email; } } // Use the api provided category terms to identify action type $category_term = $entry['category'][0]['term']; $category_label = $entry['category'][0]['label']; $log .= " Found new activity! $author_output $category_label @ $activity_time\n"; // Create new site activity object $site_activity = new ElggObject(); $site_activity->subtype = 'site_activity'; // If we have a local user for this entry, make them owner if ($local_user) { $site_activity->owner_guid = $local_user->guid; } else { // Site otherwise $site_activity->owner_guid = $group->guid; } // Set container guid & access to that of the group $site_activity->container_guid = $group->guid; $site_activity->access_id = $group->group_acl; // Set other data/metadata $site_activity->title = $title; $site_activity->site_name = $site->title; $site_activity->site_url = $site->url; $site_activity->author_name = $author_name; $site_activity->summary = $summary; // Full 'summary' element $site_activity->summary_link = $summary_link; // Category term/label $site_activity->category_term = $category_term; $site_activity->category_label = $category_label; $site_activity->updated = $activity_time; // Save the site activity item if ($site_activity->save()) { $log .= " Created new activity entity: {$site_activity->guid}\n\n"; $site_new_activity_count++; $river_id = elgg_create_river_item(array( 'view' => 'river/object/site_activity/create', 'action_type' => 'create', 'subject_guid' => $site_activity->owner_guid, 'object_guid' => $site_activity->guid, 'posted' => $activity_time )); if ($river_id) { $log .= " River entry created!\n\n"; } else { $log .= " River activity creation failed!!\n\n"; } } else { $log .= " Site activity creation failed!!\n\n"; } } } if ($site_new_activity_count) { $log .= " Created $site_new_activity_count new site_activity object(s)\n"; // Update the site's last activity time $site->last_activity_time = max($activity_times); } else { $log .= " No new activity.\n"; } } } else { $log .= "Error creating client!\n"; } } else { $log .= "ABORTING: No connected sites found.\n"; } if (elgg_in_context('googleapps_sites_log')) { echo "<pre>"; echo $log; echo "</pre>"; } return TRUE; } /** * Reset (delete) all site activity and revert site last updated times * back to connection time */ function googleapps_reset_sites_activity() { $log = "Reset Site Activity\n------------------\n"; $sites_options = array( 'type' => 'object', 'subtype' => 'site', 'limit' => 0, ); $sites = elgg_get_entities($sites_options); $sites_count = count($sites); foreach ($sites as $site) { $site->last_activity_time = $site->connected_time; $site->save(); } $log .= "\nReset update time for {$sites_count} site(s)\n"; $activity_options = array( 'type' => 'object', 'subtype' => 'site_activity', 'limit' => 0, 'count' => TRUE, ); $activity_count = elgg_get_entities($activity_options); unset($activity_options['count']); $activity_items = elgg_get_entities($activity_options); foreach ($activity_items as $activity) { elgg_delete_river(array( 'object_guid' => $activity->guid, )); $activity->delete(); } $log .= "\nDeleted {$activity_count} site_activity items(s)\n"; if (elgg_in_context('googleapps_sites_log')) { echo "<pre>"; echo $log; echo "</pre>"; } } /** * Helper function to update a local site entities information * * @param array $remote_site site info * @return mixed */ function googleapps_update_local_site_info($remote_site) { // Grab sites $site = elgg_get_entities_from_metadata(array( 'type' => 'object', 'subtype' => 'site', 'metadata_name' => 'site_id', 'metadata_value' => $remote_site['site_id'], 'limit' => 1, )); // If we've got a proper site if (count($site) >= 1 && elgg_instanceof($site[0], 'object', 'site')) { $site = $site[0]; $site->remote_owners = $remote_site['owners']; $site->modified = $remote_site['modified']; $site->url = $remote_site['url']; $site->title = $remote_site['title']; $site->save(); } return FALSE; } /** * Get events from calendar api * * @param string $calendar_id Calendar ID * @param string $class_name Class name for display in fullcalendar * @param string $start_date Event upper limit * @param string $end_date Event lower limit * @return array */ function googleapps_get_calendar_events($calendar_id, $class_name = FALSE, $start_date = FALSE, $end_date = FALSE) { if (!$calendar_id) { return FALSE; } // Get google client and load calendar API elgg_load_library('gapc:Client'); elgg_load_library('gapc:Calendar'); $client = googleapps_get_service_client(array( 'https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/calendar.readonly' )); $service = new Google_Service_Calendar($client); $optParams = array( 'showDeleted' => 0, 'maxResults' => '2500', 'singleEvents' => 1 ); // Attempt to create DateTime objects with given date strings $start_date = $start_date ? new DateTime($start_date) : FALSE; $end_date = $end_date ? new DateTime($end_date) : FALSE; // If we've got dates, format then ISO-8602 (2014-12-07T00:00:00Z) if ($start_date) { $optParams['timeMin'] = $start_date->format('c'); } if ($end_date) { $optParams['timeMax'] = $end_date->format('c'); } $events = $service->events->listEvents($calendar_id, $optParams); $event_array = array(); foreach ($events->getItems() as $item) { // Determine if this is an all day event $allDay = FALSE; if (!$item->getStart()->getDateTime()) { $allDay = true; } // Figure out start date $start_string = $item->getStart()->getDateTime() ? $item->getStart()->getDateTime() : $item->getStart()->getDate(); // Figure out end date $end_string = $item->getEnd()->getDateTime() ? $item->getEnd()->getDateTime() : $item->getEnd()->getDate(); // Format dates $start = new DateTime($start_string); $end = new DateTime($end_string); // Add event to event array $event_array[] = array( 'id' => $item->getId(), 'title' => $item->getSummary(), 'url' => $item->getHtmlLink(), 'start' => $start->format('c'), 'end' => $end->format('c'), 'allDay' => $allDay, 'location' => $item->getLocation(), 'description' => $item->getDescription(), 'className' => $class_name, 'editable' => false, ); } return $event_array; } /** * Helper function to map a google site activity 'label' to a * friendly river verb * * @param $label Human readable label from sites api, ie: deletion, move, etc * @return string */ function googleapps_get_river_verb_from_category_label($label) { $api_labels = array( 'creation' => 'created', 'deletion' => 'deleted', 'edit' => 'edited', 'move' => 'moved', 'recovery' => 'recovered', ); return $api_labels[$label] ? $api_labels[$label] : 'updated'; } /** * Joins key:value pairs by inner_glue and each pair together by outer_glue * @param string $inner_glue The HTTP method (GET, POST, PUT, DELETE) * @param string $outer_glue Full URL of the resource to access * @param array $array Associative array of query parameters * @return string Urlencoded string of query parameters */ function implode_assoc($inner_glue, $outer_glue, $array) { $output = array(); foreach($array as $key => $item) { $output[] = $key . $inner_glue . urlencode($item); } return implode($outer_glue, $output); }
THINKGlobalSchool/googleapps
lib/googleapps.php
PHP
gpl-2.0
36,538
#include "Kernel.h" #include "Hardware.h" #include "Process9.h" #include "Bootloader.h" #define LOGPM P9PM::P9PM(Process9* owner) :m_open(), m_owner(owner), handlecount(0x100000001) { } P9PM::~P9PM() { } extern FILE* openapp(u32 titlehigh, u32 titlelow); //this is from Bootloader.cpp void P9PM::Command(u32 data[],u32 numb) { u32 resdata[0x200]; memset(resdata, 0, sizeof(resdata)); u16 cmd = (data[0] >> 16); switch (cmd) { case 1: { u64 handle = (data[2] >> 0) | ((u64)(data[1]) << 32); resdata[0] = 0x00020040; auto a = m_open.list; while (a) { if (a->data->handle == handle) break; a = a->next; } if (a) { LOG("pm getexheader handle=%" PRIx64 ", titleid=%" PRIx64, handle, a->data->title); KMemoryMap* map = m_owner->m_kernel->m_IPCFIFOAdresses[(data[3] >> 4) &0xF]; resdata[1] = 0xE0000000; FILE * fd = openapp(a->data->title >> 32, (u32)a->data->title); if (fd) { //open the container char ex[0x400]; ctr_ncchheader loader_h; u32 ncch_off = 0; // Read header. if (fread(&loader_h, sizeof(loader_h), 1, fd) != 1) { XDSERROR("failed to read header."); break; } // Load NCCH if (memcmp(&loader_h.magic, "NCCH", 4) != 0) { XDSERROR("invalid magic.. wrong file?"); break; } // Read Exheader. if (fread(&ex, 0x400, 1, fd) != 1) { //this is fixed XDSERROR("failed to read exheader."); break; } for (int i = 0; i < sizeof(ex); i++) { if (map->Write8(data[4] + i, ex[i]) != Success) { break; } } resdata[1] = 0; } } else { #ifdef LOGPM LOG("pm getexheader handle=%" PRIx64, handle); #endif resdata[1] = 0xE0000000; //todo correct error } } break; case 2: { u64 title = (data[1] >> 0) | ((u64)(data[2]) << 32); #ifdef LOGPM LOG("pm register %08x %08x", data[1], data[2]); #endif if ((data[3] >> 24) != 0) LOG("register flags %02x %02x", (data[3] >> 24), (data[3 + 4] >> 24)); if (data[1] != data[1 + 4] && data[2] != data[2 + 4]) LOG("register secound %08x %08x", data[1 + 4], data[2 + 4]); struct PMOpenprocess * neone = (PMOpenprocess*)malloc(sizeof(struct PMOpenprocess)); neone->handle = handlecount++; neone->title = title; m_open.AddItem(neone); resdata[0] = 0x000200C0; resdata[1] = 0x0; resdata[2] = neone->handle >> 32; resdata[3] = (u32)neone->handle; } break; default: LOG("unknown PM cmd %08x", data[0]); break; } m_owner->Sendresponds(numb, resdata); } u64 P9PM::GetTitle(u64 handle) { auto a = m_open.list; while(a) { if(a->data->handle == handle) break; a = a->next; } if(a) { return a->data->title; } return -1; }
ichfly/XDS
source/process9/pm.cpp
C++
gpl-2.0
3,443
#include "VCTAmbientOcclusionRenderPass.h" #include "Debug/Statistics/StatisticsManager.h" #include "VCTStatisticsObject.h" bool VCTAmbientOcclusionRenderPass::IsAvailable (const RenderScene* renderScene, const Camera* camera, const RenderSettings& settings, const RenderVolumeCollection* rvc) const { /* * Always execure reflective shadow mapping indirect light render pass */ return settings.vct_ao_enabled; } std::string VCTAmbientOcclusionRenderPass::GetPostProcessFragmentShaderPath () const { return "Assets/Shaders/VoxelConeTracing/voxelConeTracingAmbientOcclusionFragment.glsl"; } std::string VCTAmbientOcclusionRenderPass::GetPostProcessVolumeName () const { return "VCTAOMap"; } glm::ivec2 VCTAmbientOcclusionRenderPass::GetPostProcessVolumeResolution (const RenderSettings& settings) const { return glm::ivec2 (glm::vec2 (settings.resolution.width, settings.resolution.height) * settings.rsm_scale); } FramebufferRenderVolume* VCTAmbientOcclusionRenderPass::CreatePostProcessVolume (const RenderSettings& settings) const { /* * Create ambient occlusion framebuffer */ Resource<Texture> texture = Resource<Texture> (new Texture ("ambientOcclusionMap")); glm::ivec2 size = GetPostProcessVolumeResolution (settings); texture->SetSize (Size (size.x, size.y)); texture->SetMipmapGeneration (false); texture->SetSizedInternalFormat (TEXTURE_SIZED_INTERNAL_FORMAT::FORMAT_R8); texture->SetInternalFormat (TEXTURE_INTERNAL_FORMAT::FORMAT_RED); texture->SetChannelType (TEXTURE_CHANNEL_TYPE::CHANNEL_UNSIGNED_BYTE); texture->SetWrapMode (TEXTURE_WRAP_MODE::WRAP_CLAMP_EDGE); texture->SetMinFilter (TEXTURE_FILTER_MODE::FILTER_NEAREST); texture->SetMagFilter (TEXTURE_FILTER_MODE::FILTER_NEAREST); texture->SetAnisotropicFiltering (false); Resource<Framebuffer> framebuffer = Resource<Framebuffer> (new Framebuffer (texture)); FramebufferRenderVolume* renderVolume = new FramebufferRenderVolume (framebuffer); /* * Update statistics object */ auto vctStatisticsObject = StatisticsManager::Instance ()->GetStatisticsObject <VCTStatisticsObject> (); vctStatisticsObject->vctAmbientOcclusionMapVolume = renderVolume; return renderVolume; } std::vector<PipelineAttribute> VCTAmbientOcclusionRenderPass::GetCustomAttributes (const Camera* camera, const RenderSettings& settings, RenderVolumeCollection* rvc) { /* * Attach post process volume attributes to pipeline */ std::vector<PipelineAttribute> attributes = PostProcessRenderPass::GetCustomAttributes (camera, settings, rvc); /* * Attach screen space ambient occlusion attributes to pipeline */ PipelineAttribute originBias; PipelineAttribute aoConeRatio; PipelineAttribute aoConeDistance; PipelineAttribute temporalFilterEnabled; originBias.type = PipelineAttribute::AttrType::ATTR_1F; aoConeRatio.type = PipelineAttribute::AttrType::ATTR_1F; aoConeDistance.type = PipelineAttribute::AttrType::ATTR_1F; temporalFilterEnabled.type = PipelineAttribute::AttrType::ATTR_1I; originBias.name = "originBias"; aoConeRatio.name = "aoConeRatio"; aoConeDistance.name = "aoConeDistance"; temporalFilterEnabled.name = "temporalFilterEnabled"; originBias.value.x = settings.vct_origin_bias; aoConeRatio.value.x = settings.vct_ao_cone_ratio; aoConeDistance.value.x = settings.vct_ao_cone_distance; temporalFilterEnabled.value.x = settings.vct_temporal_filter_enabled; attributes.push_back (originBias); attributes.push_back (aoConeRatio); attributes.push_back (aoConeDistance); attributes.push_back (temporalFilterEnabled); return attributes; }
maritim/LiteEngine
Engine/RenderPasses/VoxelConeTracing/VCTAmbientOcclusionRenderPass.cpp
C++
gpl-2.0
3,570
module AjaxUiHelper # Unobtrusive version of link_to_remote def link_to_remote( name, options, html_options={} ) html_options[:class] = "remote #{html_options.delete(:class)}".strip link_to(name, options, html_options) end def jquery_library return '' if @jquery_library_loaded @jquery_library_loaded = true javascript_include_tag( 'jquery/jquery-1.2.6.min.js' ) + javascript_tag( 'var jQ$ = jQuery.noConflict();' ) end def prototype_library return '' if @prototype_library_loaded @prototype_library_loaded = true javascript_include_tag 'prototype' end def jquery_effects return '' if @jquery_effects_loaded @jquery_effects_loaded = true jquery_library + javascript_include_tag( 'jquery/ui/minified/effects.core.min.js' ) + javascript_include_tag( 'jquery/ui/minified/effects.slide.min.js' ) + javascript_include_tag( 'jquery/ui/minified/effects.drop.min.js' ) end # load the javascript tabs. redefine the method when you're done so it can't be called again def load_javascript_tabs return if @javascript_tabs_loaded content_for :javascript, jquery_effects + javascript_include_tag('tabs') content_for :javascript_onload, "Crabgrass.Tabs.initialize_tab_blocks();" @javascript_tabs_loaded = true end def load_ajax_form_behaviors return if @ajax_form_behavior_loaded content_for :javascript, javascript_include_tag( 'forms' ) content_for :javascript_onload, 'Crabgrass.Forms.initialize_radio_behavior(); Crabgrass.Forms.initialize_remote_actions();' @ajax_form_behavior_loaded = true end def load_ajax_list_behaviors return if @ajax_list_behavior_loaded content_for( :javascript, jquery_library + javascript_tag( <<-SCRIPT jQ$('ul.list .toolbar .delete.confirm').click( function( ev ) { return confirm( 'You are about to delete this item. You will not be able to undo this.' ); }); SCRIPT )) @ajax_list_behavior_loaded = true end def load_markitup_library content_for( :stylesheet, stylesheet_link_tag( '../javascripts/markitup/skins/greenchange/style-full' ) + stylesheet_link_tag( '../javascripts/markitup/sets/textile/style' )) content_for( :javascript, jquery_library + javascript_include_tag( 'markitup/jquery.markitup.preview.min.js' ) + javascript_include_tag( 'markitup/sets/textile/parser' ) + javascript_include_tag( 'markitup/sets/textile/set' ) ) end end
mikeymicrophone/greenchange
app/helpers/ajax_ui_helper.rb
Ruby
gpl-2.0
2,523
<html> <pre> <?php print_r($_REQUEST); if( isset( $_REQUEST['ip'] ) && isset ( $_REQUEST['mac'] ) ) { $ip = $_REQUEST['ip']; $mac = $_REQUEST['mac']; exec("sudo iptables -I internet 1 -t mangle -m mac --mac-source $mac -j RETURN"); exec("sudo rmtrack " . $ip); echo "User logged in."; exit; } else { echo "Access Denied"; exit; } ?>
thgh/pilon
www/process.php
PHP
gpl-2.0
363
/* ------------------ BASE STYLES ------------------ */ html, body { height: 100%; width: 100%; } body { font-family: "Open Sans", sans-serif; font-size: 16px; font-weight: 300; color: #777777; background-color: #fff !important; line-height: 1.6; } body.fullscreen-image-background { background-image: url('../img/sliders/slider1.jpg?1394417052'); background-size: cover; background-repeat: no-repeat; background-position: center center; } @media screen and (min-width: 1025px) { body.fullscreen-image-background { background-attachment: fixed; } } h1, h2, h3, h4, h5, h6 { font-family: "Dosis", sans-serif; font-weight: 300; color: #646464; margin-top: 0; } /* ------------------ GENERAL STYLES ------------------ */ @font-face { font-family: "brankic"; src: url('../fonts/brankic.eot'); src: url('../fonts/brankic.eot?#iefix') format('eot'), url('../fonts/brankic.svg') format('svg'), url('../fonts/brankic.ttf') format('truetype'), url('../fonts/brankic.woff') format('woff'); } /* --------------------- */ /* NAVIGATION BAR /* --------------------- */ .navbar-brand { padding: 10px 15px; } .navbar-brand img { width: 74px; height: auto; } .navbar, .navbar.navbar-light { -webkit-transition-property: all; -moz-transition-property: all; -o-transition-property: all; transition-property: all; -webkit-transition-duration: 0.2s; -moz-transition-duration: 0.2s; -o-transition-duration: 0.2s; transition-duration: 0.2s; -webkit-transition-timing-function: linear; -moz-transition-timing-function: linear; -o-transition-timing-function: linear; transition-timing-function: linear; } .navbar-nav { padding: 10px 0; } .navbar-nav > li { margin: 0 10px; } .navbar-nav > li > a { -webkit-transition-property: all; -moz-transition-property: all; -o-transition-property: all; transition-property: all; -webkit-transition-duration: 0.1s; -moz-transition-duration: 0.1s; -o-transition-duration: 0.1s; transition-duration: 0.1s; -webkit-transition-timing-function: ease-out; -moz-transition-timing-function: ease-out; -o-transition-timing-function: ease-out; transition-timing-function: ease-out; padding-left: 3px; padding-right: 3px; padding-top: 5px; padding-bottom: 5px; border-bottom: 2px solid rgba(0, 0, 0, 0); font-size: 12px; color: #646464; font-weight: 700; } .navbar-nav > li > a:hover, .navbar-nav > li > a:focus { border-bottom: 2px solid #646464; padding-bottom: 0; background-color: transparent; } .navbar-nav > li.active > a { border-bottom: 2px solid #646464; padding-bottom: 0; background-color: transparent; } .navbar-nav.nav-text-light > li > a { color: #fff; } .navbar-nav.nav-text-light > li > a:hover { border-bottom-color: #fff; } .navbar-nav.nav-text-light > li.active > a { border-bottom-color: #fff; } .navbar { -webkit-border-radius: 0; -moz-border-radius: 0; -ms-border-radius: 0; -o-border-radius: 0; border-radius: 0; } .navbar.navbar-light { background-color: #f7f7f7; border-bottom: 1px solid #eee; } .navbar.navbar-light .navbar-nav.nav-text-light > li > a { color: #646464; } @media screen and (max-width: 767px) { .navbar.navbar-light .navbar-nav.nav-text-light > li > a { color: #e6e6e6; border-bottom: none; padding-top: 15px; padding-bottom: 15px; } .navbar.navbar-light .navbar-nav.nav-text-light > li > a:hover { color: #fff; padding-top: 15px; padding-bottom: 15px; text-decoration: underline; } } .navbar.navbar-light .navbar-nav.nav-text-light > li > a:hover { border-bottom-color: #646464; } .navbar.navbar-light .navbar-nav.nav-text-light > li.active > a { border-bottom-color: #646464; } .navbar-toggle { background-color: #646464; } .navbar-toggle .icon-bar { background-color: #fff; } @media screen and (max-width: 767px) { .navbar-collapse { background-color: #646464; } } /* --------------------- */ /* BUTTONS /* --------------------- */ .btn { -webkit-border-radius: 0; -moz-border-radius: 0; -ms-border-radius: 0; -o-border-radius: 0; border-radius: 0; -webkit-transition-property: border-color; -moz-transition-property: border-color; -o-transition-property: border-color; transition-property: border-color; -webkit-transition-duration: 0.2s; -moz-transition-duration: 0.2s; -o-transition-duration: 0.2s; transition-duration: 0.2s; -webkit-transition-timing-function: linear; -moz-transition-timing-function: linear; -o-transition-timing-function: linear; transition-timing-function: linear; } .btn-lg { border-width: 6px; } .btn-sm { border-width: 3px; } .btn-xs { border-width: 2px; } .btn-info { background-color: #00aeef; border-color: #00aeef; } .btn-info:hover, .btn-info:focus, .btn-info:active, .btn-info.active { background-color: #00aeef; border-color: #009bd5; } .btn-primary { background-color: #ffae3f; border-color: #ffae3f; } .btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active { background-color: #ffae3f; border-color: #ffa325; } .btn-primary.disabled, .btn-primary[disabled] { background-color: #ffc472; border-color: #ffae3f; } .btn-primary.disabled:hover, .btn-primary.disabled:focus, .btn-primary.disabled:active, .btn-primary.disabled.active, .btn-primary[disabled]:hover, .btn-primary[disabled]:focus, .btn-primary[disabled]:active, .btn-primary[disabled].active { background-color: #ffc472; border-color: #ffae3f; } /* --------------------- */ /* LINKS /* --------------------- */ a { color: #ffae3f; } a:hover, a:focus { color: #ffc472; text-decoration: none; } /* --------------------- */ /* SECTION /* --------------------- */ .section { background-color: #fafafa; padding: 70px 0; } .section.darker { background-color: whitesmoke; } .section.most-dark { background-color: #4d4d4d; color: #fafafa; } .section-heading { text-align: center; margin-bottom: 50px; } .section-heading h2, .section-heading p { font-family: "Dosis", sans-serif; } .section-heading h2 { font-size: 3em; color: #ffae3f; } .section-heading p { font-size: 1.5em; color: #c2c2c2; } .section-heading hr { display: -moz-inline-stack; display: inline-block; vertical-align: middle; *vertical-align: auto; zoom: 1; *display: inline; width: 100px; border-top: 1px solid #646464; } .section-content h3 { color: #c2c2c2; } .section-content .sub-section { margin-top: 30px; } /* --------------------- */ /* TOOLTIP /* --------------------- */ .tooltip-inner { filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=50); opacity: 0.5; } .tooltip.top .tooltip-arrow, .tooltip.top-left .tooltip-arrow, .tooltip.top-right .tooltip-arrow, .tooltip.right .tooltip-arrow, .tooltip.left .tooltip-arrow, .tooltip.bottom .tooltip-arrow, .tooltip.bottom-left .tooltip-arrow, .tooltip.bottom-right .tooltip-arrow { filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=50); opacity: 0.5; } /* --------------------- */ /* 3rd PARTY STYLES /* --------------------- */ .parallax { background-attachment: fixed !important; background-size: cover; } @media screen and (max-width: 1024px) { .parallax { background-attachment: scroll !important; background-position: initial !important; background-repeat: no-repeat !important; } } .wow { visibility: hidden; } body #jpreLoader { left: 0 !important; width: 100%; height: 1px; } body #jprePercentage { height: auto; top: -80px; font-size: 48px; font-weight: normal; font-family: "Dosis", sans-serif; text-shadow: none; color: #777777; } body #jpreOverlay { background-color: #fafafa; } body #jpreBar { -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; background-image: none; background-color: #777777; } .parsley-error-list { list-style-type: none; } .parsley-error-list li { font-size: 12px; color: #d2322d; } /* Supersized - Fullscreen Slideshow jQuery Plugin Version : 3.2.7 Site : www.buildinternet.com/project/supersized Author : Sam Dunn Company : One Mighty Roar (www.onemightyroar.com) License : MIT License / GPL License */ * { margin: 0; padding: 0; } body { background: #111; height: 100%; } img { border: none; } #supersized-loader { position: absolute; top: 50%; left: 50%; z-index: 0; width: 60px; height: 60px; margin: -30px 0 0 -30px; text-indent: -999em; background: url(../img/progress.gif) no-repeat center center; } #supersized { display: block; position: fixed; left: 0; top: 0; overflow: hidden; z-index: -999; height: 100%; width: 100%; } #supersized img { width: auto; height: auto; position: relative; display: none; outline: none; border: none; } #supersized.speed img { -ms-interpolation-mode: nearest-neighbor; image-rendering: -moz-crisp-edges; } /*Speed*/ #supersized.quality img { -ms-interpolation-mode: bicubic; image-rendering: optimizeQuality; } /*Quality*/ #supersized li { display: block; list-style: none; z-index: -30; position: fixed; overflow: hidden; top: 0; left: 0; width: 100%; height: 100%; background: #111; } #supersized a { width: 100%; height: 100%; display: block; } #supersized li.prevslide { z-index: -20; } #supersized li.activeslide { z-index: -10; } #supersized li.image-loading { background: #111111 url(../img/progress.gif) no-repeat center center; width: 100%; height: 100%; } #supersized li.image-loading img { visibility: hidden; } #supersized li.prevslide img, #supersized li.activeslide img { display: inline; } /* * Font Awesome 4.0.3 by @davegandy - http://fontawesome.io - @fontawesome * License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License) */ @font-face { font-family: 'FontAwesome'; src: url("../fonts/fontawesome-webfont.eot?v=4.0.3"); src: url("../fonts/fontawesome-webfont.eot?#iefix&v=4.0.3") format("embedded-opentype"), url("../fonts/fontawesome-webfont.woff?v=4.0.3") format("woff"), url("../fonts/fontawesome-webfont.ttf?v=4.0.3") format("truetype"), url("../fonts/fontawesome-webfont.svg?v=4.0.3#fontawesomeregular") format("svg"); font-weight: normal; font-style: normal; } .fa { display: inline-block; font-family: FontAwesome; font-style: normal; font-weight: normal; line-height: 1; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .fa-lg { font-size: 1.3333333333333333em; line-height: .75em; vertical-align: -15%; } .fa-2x { font-size: 2em; } .fa-3x { font-size: 3em; } .fa-4x { font-size: 4em; } .fa-5x { font-size: 5em; } .fa-fw { width: 1.2857142857142858em; text-align: center; } .fa-ul { padding-left: 0; margin-left: 2.142857142857143em; list-style-type: none; } .fa-ul > li { position: relative; } .fa-li { position: absolute; left: -2.142857142857143em; width: 2.142857142857143em; top: .14285714285714285em; text-align: center; } .fa-li.fa-lg { left: -1.8571428571428572em; } .fa-border { padding: .2em .25em .15em; border: solid .08em #eee; border-radius: .1em; } .pull-right { float: right; } .pull-left { float: left; } .fa.pull-left { margin-right: .3em; } .fa.pull-right { margin-left: .3em; } .fa-spin { -webkit-animation: spin 2s infinite linear; -moz-animation: spin 2s infinite linear; -o-animation: spin 2s infinite linear; animation: spin 2s infinite linear; } @-moz-keyframes spin { 0% { -moz-transform: rotate(0deg); } 100% { -moz-transform: rotate(359deg); } } @-webkit-keyframes spin { 0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(359deg); } } @-o-keyframes spin { 0% { -o-transform: rotate(0deg); } 100% { -o-transform: rotate(359deg); } } @-ms-keyframes spin { 0% { -ms-transform: rotate(0deg); } 100% { -ms-transform: rotate(359deg); } } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(359deg); } } .fa-rotate-90 { filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1); -webkit-transform: rotate(90deg); -moz-transform: rotate(90deg); -ms-transform: rotate(90deg); -o-transform: rotate(90deg); transform: rotate(90deg); } .fa-rotate-180 { filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2); -webkit-transform: rotate(180deg); -moz-transform: rotate(180deg); -ms-transform: rotate(180deg); -o-transform: rotate(180deg); transform: rotate(180deg); } .fa-rotate-270 { filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); -webkit-transform: rotate(270deg); -moz-transform: rotate(270deg); -ms-transform: rotate(270deg); -o-transform: rotate(270deg); transform: rotate(270deg); } .fa-flip-horizontal { filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=0,mirror=1); -webkit-transform: scale(-1, 1); -moz-transform: scale(-1, 1); -ms-transform: scale(-1, 1); -o-transform: scale(-1, 1); transform: scale(-1, 1); } .fa-flip-vertical { filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2,mirror=1); -webkit-transform: scale(1, -1); -moz-transform: scale(1, -1); -ms-transform: scale(1, -1); -o-transform: scale(1, -1); transform: scale(1, -1); } .fa-stack { position: relative; display: inline-block; width: 2em; height: 2em; line-height: 2em; vertical-align: middle; } .fa-stack-1x, .fa-stack-2x { position: absolute; left: 0; width: 100%; text-align: center; } .fa-stack-1x { line-height: inherit; } .fa-stack-2x { font-size: 2em; } .fa-inverse { color: #fff; } .fa-glass:before { content: "\f000"; } .fa-music:before { content: "\f001"; } .fa-search:before { content: "\f002"; } .fa-envelope-o:before { content: "\f003"; } .fa-heart:before { content: "\f004"; } .fa-star:before { content: "\f005"; } .fa-star-o:before { content: "\f006"; } .fa-user:before { content: "\f007"; } .fa-film:before { content: "\f008"; } .fa-th-large:before { content: "\f009"; } .fa-th:before { content: "\f00a"; } .fa-th-list:before { content: "\f00b"; } .fa-check:before { content: "\f00c"; } .fa-times:before { content: "\f00d"; } .fa-search-plus:before { content: "\f00e"; } .fa-search-minus:before { content: "\f010"; } .fa-power-off:before { content: "\f011"; } .fa-signal:before { content: "\f012"; } .fa-gear:before, .fa-cog:before { content: "\f013"; } .fa-trash-o:before { content: "\f014"; } .fa-home:before { content: "\f015"; } .fa-file-o:before { content: "\f016"; } .fa-clock-o:before { content: "\f017"; } .fa-road:before { content: "\f018"; } .fa-download:before { content: "\f019"; } .fa-arrow-circle-o-down:before { content: "\f01a"; } .fa-arrow-circle-o-up:before { content: "\f01b"; } .fa-inbox:before { content: "\f01c"; } .fa-play-circle-o:before { content: "\f01d"; } .fa-rotate-right:before, .fa-repeat:before { content: "\f01e"; } .fa-refresh:before { content: "\f021"; } .fa-list-alt:before { content: "\f022"; } .fa-lock:before { content: "\f023"; } .fa-flag:before { content: "\f024"; } .fa-headphones:before { content: "\f025"; } .fa-volume-off:before { content: "\f026"; } .fa-volume-down:before { content: "\f027"; } .fa-volume-up:before { content: "\f028"; } .fa-qrcode:before { content: "\f029"; } .fa-barcode:before { content: "\f02a"; } .fa-tag:before { content: "\f02b"; } .fa-tags:before { content: "\f02c"; } .fa-book:before { content: "\f02d"; } .fa-bookmark:before { content: "\f02e"; } .fa-print:before { content: "\f02f"; } .fa-camera:before { content: "\f030"; } .fa-font:before { content: "\f031"; } .fa-bold:before { content: "\f032"; } .fa-italic:before { content: "\f033"; } .fa-text-height:before { content: "\f034"; } .fa-text-width:before { content: "\f035"; } .fa-align-left:before { content: "\f036"; } .fa-align-center:before { content: "\f037"; } .fa-align-right:before { content: "\f038"; } .fa-align-justify:before { content: "\f039"; } .fa-list:before { content: "\f03a"; } .fa-dedent:before, .fa-outdent:before { content: "\f03b"; } .fa-indent:before { content: "\f03c"; } .fa-video-camera:before { content: "\f03d"; } .fa-picture-o:before { content: "\f03e"; } .fa-pencil:before { content: "\f040"; } .fa-map-marker:before { content: "\f041"; } .fa-adjust:before { content: "\f042"; } .fa-tint:before { content: "\f043"; } .fa-edit:before, .fa-pencil-square-o:before { content: "\f044"; } .fa-share-square-o:before { content: "\f045"; } .fa-check-square-o:before { content: "\f046"; } .fa-arrows:before { content: "\f047"; } .fa-step-backward:before { content: "\f048"; } .fa-fast-backward:before { content: "\f049"; } .fa-backward:before { content: "\f04a"; } .fa-play:before { content: "\f04b"; } .fa-pause:before { content: "\f04c"; } .fa-stop:before { content: "\f04d"; } .fa-forward:before { content: "\f04e"; } .fa-fast-forward:before { content: "\f050"; } .fa-step-forward:before { content: "\f051"; } .fa-eject:before { content: "\f052"; } .fa-chevron-left:before { content: "\f053"; } .fa-chevron-right:before { content: "\f054"; } .fa-plus-circle:before { content: "\f055"; } .fa-minus-circle:before { content: "\f056"; } .fa-times-circle:before { content: "\f057"; } .fa-check-circle:before { content: "\f058"; } .fa-question-circle:before { content: "\f059"; } .fa-info-circle:before { content: "\f05a"; } .fa-crosshairs:before { content: "\f05b"; } .fa-times-circle-o:before { content: "\f05c"; } .fa-check-circle-o:before { content: "\f05d"; } .fa-ban:before { content: "\f05e"; } .fa-arrow-left:before { content: "\f060"; } .fa-arrow-right:before { content: "\f061"; } .fa-arrow-up:before { content: "\f062"; } .fa-arrow-down:before { content: "\f063"; } .fa-mail-forward:before, .fa-share:before { content: "\f064"; } .fa-expand:before { content: "\f065"; } .fa-compress:before { content: "\f066"; } .fa-plus:before { content: "\f067"; } .fa-minus:before { content: "\f068"; } .fa-asterisk:before { content: "\f069"; } .fa-exclamation-circle:before { content: "\f06a"; } .fa-gift:before { content: "\f06b"; } .fa-leaf:before { content: "\f06c"; } .fa-fire:before { content: "\f06d"; } .fa-eye:before { content: "\f06e"; } .fa-eye-slash:before { content: "\f070"; } .fa-warning:before, .fa-exclamation-triangle:before { content: "\f071"; } .fa-plane:before { content: "\f072"; } .fa-calendar:before { content: "\f073"; } .fa-random:before { content: "\f074"; } .fa-comment:before { content: "\f075"; } .fa-magnet:before { content: "\f076"; } .fa-chevron-up:before { content: "\f077"; } .fa-chevron-down:before { content: "\f078"; } .fa-retweet:before { content: "\f079"; } .fa-shopping-cart:before { content: "\f07a"; } .fa-folder:before { content: "\f07b"; } .fa-folder-open:before { content: "\f07c"; } .fa-arrows-v:before { content: "\f07d"; } .fa-arrows-h:before { content: "\f07e"; } .fa-bar-chart-o:before { content: "\f080"; } .fa-twitter-square:before { content: "\f081"; } .fa-facebook-square:before { content: "\f082"; } .fa-camera-retro:before { content: "\f083"; } .fa-key:before { content: "\f084"; } .fa-gears:before, .fa-cogs:before { content: "\f085"; } .fa-comments:before { content: "\f086"; } .fa-thumbs-o-up:before { content: "\f087"; } .fa-thumbs-o-down:before { content: "\f088"; } .fa-star-half:before { content: "\f089"; } .fa-heart-o:before { content: "\f08a"; } .fa-sign-out:before { content: "\f08b"; } .fa-linkedin-square:before { content: "\f08c"; } .fa-thumb-tack:before { content: "\f08d"; } .fa-external-link:before { content: "\f08e"; } .fa-sign-in:before { content: "\f090"; } .fa-trophy:before { content: "\f091"; } .fa-github-square:before { content: "\f092"; } .fa-upload:before { content: "\f093"; } .fa-lemon-o:before { content: "\f094"; } .fa-phone:before { content: "\f095"; } .fa-square-o:before { content: "\f096"; } .fa-bookmark-o:before { content: "\f097"; } .fa-phone-square:before { content: "\f098"; } .fa-twitter:before { content: "\f099"; } .fa-facebook:before { content: "\f09a"; } .fa-github:before { content: "\f09b"; } .fa-unlock:before { content: "\f09c"; } .fa-credit-card:before { content: "\f09d"; } .fa-rss:before { content: "\f09e"; } .fa-hdd-o:before { content: "\f0a0"; } .fa-bullhorn:before { content: "\f0a1"; } .fa-bell:before { content: "\f0f3"; } .fa-certificate:before { content: "\f0a3"; } .fa-hand-o-right:before { content: "\f0a4"; } .fa-hand-o-left:before { content: "\f0a5"; } .fa-hand-o-up:before { content: "\f0a6"; } .fa-hand-o-down:before { content: "\f0a7"; } .fa-arrow-circle-left:before { content: "\f0a8"; } .fa-arrow-circle-right:before { content: "\f0a9"; } .fa-arrow-circle-up:before { content: "\f0aa"; } .fa-arrow-circle-down:before { content: "\f0ab"; } .fa-globe:before { content: "\f0ac"; } .fa-wrench:before { content: "\f0ad"; } .fa-tasks:before { content: "\f0ae"; } .fa-filter:before { content: "\f0b0"; } .fa-briefcase:before { content: "\f0b1"; } .fa-arrows-alt:before { content: "\f0b2"; } .fa-group:before, .fa-users:before { content: "\f0c0"; } .fa-chain:before, .fa-link:before { content: "\f0c1"; } .fa-cloud:before { content: "\f0c2"; } .fa-flask:before { content: "\f0c3"; } .fa-cut:before, .fa-scissors:before { content: "\f0c4"; } .fa-copy:before, .fa-files-o:before { content: "\f0c5"; } .fa-paperclip:before { content: "\f0c6"; } .fa-save:before, .fa-floppy-o:before { content: "\f0c7"; } .fa-square:before { content: "\f0c8"; } .fa-bars:before { content: "\f0c9"; } .fa-list-ul:before { content: "\f0ca"; } .fa-list-ol:before { content: "\f0cb"; } .fa-strikethrough:before { content: "\f0cc"; } .fa-underline:before { content: "\f0cd"; } .fa-table:before { content: "\f0ce"; } .fa-magic:before { content: "\f0d0"; } .fa-truck:before { content: "\f0d1"; } .fa-pinterest:before { content: "\f0d2"; } .fa-pinterest-square:before { content: "\f0d3"; } .fa-google-plus-square:before { content: "\f0d4"; } .fa-google-plus:before { content: "\f0d5"; } .fa-money:before { content: "\f0d6"; } .fa-caret-down:before { content: "\f0d7"; } .fa-caret-up:before { content: "\f0d8"; } .fa-caret-left:before { content: "\f0d9"; } .fa-caret-right:before { content: "\f0da"; } .fa-columns:before { content: "\f0db"; } .fa-unsorted:before, .fa-sort:before { content: "\f0dc"; } .fa-sort-down:before, .fa-sort-asc:before { content: "\f0dd"; } .fa-sort-up:before, .fa-sort-desc:before { content: "\f0de"; } .fa-envelope:before { content: "\f0e0"; } .fa-linkedin:before { content: "\f0e1"; } .fa-rotate-left:before, .fa-undo:before { content: "\f0e2"; } .fa-legal:before, .fa-gavel:before { content: "\f0e3"; } .fa-dashboard:before, .fa-tachometer:before { content: "\f0e4"; } .fa-comment-o:before { content: "\f0e5"; } .fa-comments-o:before { content: "\f0e6"; } .fa-flash:before, .fa-bolt:before { content: "\f0e7"; } .fa-sitemap:before { content: "\f0e8"; } .fa-umbrella:before { content: "\f0e9"; } .fa-paste:before, .fa-clipboard:before { content: "\f0ea"; } .fa-lightbulb-o:before { content: "\f0eb"; } .fa-exchange:before { content: "\f0ec"; } .fa-cloud-download:before { content: "\f0ed"; } .fa-cloud-upload:before { content: "\f0ee"; } .fa-user-md:before { content: "\f0f0"; } .fa-stethoscope:before { content: "\f0f1"; } .fa-suitcase:before { content: "\f0f2"; } .fa-bell-o:before { content: "\f0a2"; } .fa-coffee:before { content: "\f0f4"; } .fa-cutlery:before { content: "\f0f5"; } .fa-file-text-o:before { content: "\f0f6"; } .fa-building-o:before { content: "\f0f7"; } .fa-hospital-o:before { content: "\f0f8"; } .fa-ambulance:before { content: "\f0f9"; } .fa-medkit:before { content: "\f0fa"; } .fa-fighter-jet:before { content: "\f0fb"; } .fa-beer:before { content: "\f0fc"; } .fa-h-square:before { content: "\f0fd"; } .fa-plus-square:before { content: "\f0fe"; } .fa-angle-double-left:before { content: "\f100"; } .fa-angle-double-right:before { content: "\f101"; } .fa-angle-double-up:before { content: "\f102"; } .fa-angle-double-down:before { content: "\f103"; } .fa-angle-left:before { content: "\f104"; } .fa-angle-right:before { content: "\f105"; } .fa-angle-up:before { content: "\f106"; } .fa-angle-down:before { content: "\f107"; } .fa-desktop:before { content: "\f108"; } .fa-laptop:before { content: "\f109"; } .fa-tablet:before { content: "\f10a"; } .fa-mobile-phone:before, .fa-mobile:before { content: "\f10b"; } .fa-circle-o:before { content: "\f10c"; } .fa-quote-left:before { content: "\f10d"; } .fa-quote-right:before { content: "\f10e"; } .fa-spinner:before { content: "\f110"; } .fa-circle:before { content: "\f111"; } .fa-mail-reply:before, .fa-reply:before { content: "\f112"; } .fa-github-alt:before { content: "\f113"; } .fa-folder-o:before { content: "\f114"; } .fa-folder-open-o:before { content: "\f115"; } .fa-smile-o:before { content: "\f118"; } .fa-frown-o:before { content: "\f119"; } .fa-meh-o:before { content: "\f11a"; } .fa-gamepad:before { content: "\f11b"; } .fa-keyboard-o:before { content: "\f11c"; } .fa-flag-o:before { content: "\f11d"; } .fa-flag-checkered:before { content: "\f11e"; } .fa-terminal:before { content: "\f120"; } .fa-code:before { content: "\f121"; } .fa-reply-all:before { content: "\f122"; } .fa-mail-reply-all:before { content: "\f122"; } .fa-star-half-empty:before, .fa-star-half-full:before, .fa-star-half-o:before { content: "\f123"; } .fa-location-arrow:before { content: "\f124"; } .fa-crop:before { content: "\f125"; } .fa-code-fork:before { content: "\f126"; } .fa-unlink:before, .fa-chain-broken:before { content: "\f127"; } .fa-question:before { content: "\f128"; } .fa-info:before { content: "\f129"; } .fa-exclamation:before { content: "\f12a"; } .fa-superscript:before { content: "\f12b"; } .fa-subscript:before { content: "\f12c"; } .fa-eraser:before { content: "\f12d"; } .fa-puzzle-piece:before { content: "\f12e"; } .fa-microphone:before { content: "\f130"; } .fa-microphone-slash:before { content: "\f131"; } .fa-shield:before { content: "\f132"; } .fa-calendar-o:before { content: "\f133"; } .fa-fire-extinguisher:before { content: "\f134"; } .fa-rocket:before { content: "\f135"; } .fa-maxcdn:before { content: "\f136"; } .fa-chevron-circle-left:before { content: "\f137"; } .fa-chevron-circle-right:before { content: "\f138"; } .fa-chevron-circle-up:before { content: "\f139"; } .fa-chevron-circle-down:before { content: "\f13a"; } .fa-html5:before { content: "\f13b"; } .fa-css3:before { content: "\f13c"; } .fa-anchor:before { content: "\f13d"; } .fa-unlock-alt:before { content: "\f13e"; } .fa-bullseye:before { content: "\f140"; } .fa-ellipsis-h:before { content: "\f141"; } .fa-ellipsis-v:before { content: "\f142"; } .fa-rss-square:before { content: "\f143"; } .fa-play-circle:before { content: "\f144"; } .fa-ticket:before { content: "\f145"; } .fa-minus-square:before { content: "\f146"; } .fa-minus-square-o:before { content: "\f147"; } .fa-level-up:before { content: "\f148"; } .fa-level-down:before { content: "\f149"; } .fa-check-square:before { content: "\f14a"; } .fa-pencil-square:before { content: "\f14b"; } .fa-external-link-square:before { content: "\f14c"; } .fa-share-square:before { content: "\f14d"; } .fa-compass:before { content: "\f14e"; } .fa-toggle-down:before, .fa-caret-square-o-down:before { content: "\f150"; } .fa-toggle-up:before, .fa-caret-square-o-up:before { content: "\f151"; } .fa-toggle-right:before, .fa-caret-square-o-right:before { content: "\f152"; } .fa-euro:before, .fa-eur:before { content: "\f153"; } .fa-gbp:before { content: "\f154"; } .fa-dollar:before, .fa-usd:before { content: "\f155"; } .fa-rupee:before, .fa-inr:before { content: "\f156"; } .fa-cny:before, .fa-rmb:before, .fa-yen:before, .fa-jpy:before { content: "\f157"; } .fa-ruble:before, .fa-rouble:before, .fa-rub:before { content: "\f158"; } .fa-won:before, .fa-krw:before { content: "\f159"; } .fa-bitcoin:before, .fa-btc:before { content: "\f15a"; } .fa-file:before { content: "\f15b"; } .fa-file-text:before { content: "\f15c"; } .fa-sort-alpha-asc:before { content: "\f15d"; } .fa-sort-alpha-desc:before { content: "\f15e"; } .fa-sort-amount-asc:before { content: "\f160"; } .fa-sort-amount-desc:before { content: "\f161"; } .fa-sort-numeric-asc:before { content: "\f162"; } .fa-sort-numeric-desc:before { content: "\f163"; } .fa-thumbs-up:before { content: "\f164"; } .fa-thumbs-down:before { content: "\f165"; } .fa-youtube-square:before { content: "\f166"; } .fa-youtube:before { content: "\f167"; } .fa-xing:before { content: "\f168"; } .fa-xing-square:before { content: "\f169"; } .fa-youtube-play:before { content: "\f16a"; } .fa-dropbox:before { content: "\f16b"; } .fa-stack-overflow:before { content: "\f16c"; } .fa-instagram:before { content: "\f16d"; } .fa-flickr:before { content: "\f16e"; } .fa-adn:before { content: "\f170"; } .fa-bitbucket:before { content: "\f171"; } .fa-bitbucket-square:before { content: "\f172"; } .fa-tumblr:before { content: "\f173"; } .fa-tumblr-square:before { content: "\f174"; } .fa-long-arrow-down:before { content: "\f175"; } .fa-long-arrow-up:before { content: "\f176"; } .fa-long-arrow-left:before { content: "\f177"; } .fa-long-arrow-right:before { content: "\f178"; } .fa-apple:before { content: "\f179"; } .fa-windows:before { content: "\f17a"; } .fa-android:before { content: "\f17b"; } .fa-linux:before { content: "\f17c"; } .fa-dribbble:before { content: "\f17d"; } .fa-skype:before { content: "\f17e"; } .fa-foursquare:before { content: "\f180"; } .fa-trello:before { content: "\f181"; } .fa-female:before { content: "\f182"; } .fa-male:before { content: "\f183"; } .fa-gittip:before { content: "\f184"; } .fa-sun-o:before { content: "\f185"; } .fa-moon-o:before { content: "\f186"; } .fa-archive:before { content: "\f187"; } .fa-bug:before { content: "\f188"; } .fa-vk:before { content: "\f189"; } .fa-weibo:before { content: "\f18a"; } .fa-renren:before { content: "\f18b"; } .fa-pagelines:before { content: "\f18c"; } .fa-stack-exchange:before { content: "\f18d"; } .fa-arrow-circle-o-right:before { content: "\f18e"; } .fa-arrow-circle-o-left:before { content: "\f190"; } .fa-toggle-left:before, .fa-caret-square-o-left:before { content: "\f191"; } .fa-dot-circle-o:before { content: "\f192"; } .fa-wheelchair:before { content: "\f193"; } .fa-vimeo-square:before { content: "\f194"; } .fa-turkish-lira:before, .fa-try:before { content: "\f195"; } .fa-plus-square-o:before { content: "\f196"; } [class^="icon-"], [class*=" icon-"] { font-family: 'brankic'; speak: none; font-style: normal; font-weight: normal; font-variant: normal; text-transform: none; line-height: 1; /* Better Font Rendering =========== */ -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .icon-number:before { content: "\e600"; } .icon-number2:before { content: "\e601"; } .icon-number3:before { content: "\e602"; } .icon-number4:before { content: "\e603"; } .icon-number5:before { content: "\e604"; } .icon-number6:before { content: "\e605"; } .icon-number7:before { content: "\e606"; } .icon-number8:before { content: "\e607"; } .icon-number9:before { content: "\e608"; } .icon-number10:before { content: "\e609"; } .icon-number11:before { content: "\e60a"; } .icon-number12:before { content: "\e60b"; } .icon-number13:before { content: "\e60c"; } .icon-number14:before { content: "\e60d"; } .icon-number15:before { content: "\e60e"; } .icon-number16:before { content: "\e60f"; } .icon-number17:before { content: "\e610"; } .icon-number18:before { content: "\e611"; } .icon-number19:before { content: "\e612"; } .icon-number20:before { content: "\e613"; } .icon-quote:before { content: "\e614"; } .icon-quote2:before { content: "\e615"; } .icon-tag:before { content: "\e616"; } .icon-tag2:before { content: "\e617"; } .icon-link:before { content: "\e618"; } .icon-link2:before { content: "\e619"; } .icon-cabinet:before { content: "\e61a"; } .icon-cabinet2:before { content: "\e61b"; } .icon-calendar:before { content: "\e61c"; } .icon-calendar2:before { content: "\e61d"; } .icon-calendar3:before { content: "\e61e"; } .icon-file:before { content: "\e61f"; } .icon-file2:before { content: "\e620"; } .icon-file3:before { content: "\e621"; } .icon-files:before { content: "\e622"; } .icon-phone:before { content: "\e623"; } .icon-tablet:before { content: "\e624"; } .icon-window:before { content: "\e625"; } .icon-monitor:before { content: "\e626"; } .icon-ipod:before { content: "\e627"; } .icon-tv:before { content: "\e628"; } .icon-camera:before { content: "\e629"; } .icon-camera2:before { content: "\e62a"; } .icon-camera3:before { content: "\e62b"; } .icon-film:before { content: "\e62c"; } .icon-film2:before { content: "\e62d"; } .icon-film3:before { content: "\e62e"; } .icon-microphone:before { content: "\e62f"; } .icon-microphone2:before { content: "\e630"; } .icon-microphone3:before { content: "\e631"; } .icon-drink:before { content: "\e632"; } .icon-drink2:before { content: "\e633"; } .icon-drink3:before { content: "\e634"; } .icon-drink4:before { content: "\e635"; } .icon-coffee:before { content: "\e636"; } .icon-mug:before { content: "\e637"; } .icon-ice-cream:before { content: "\e638"; } .icon-cake:before { content: "\e639"; } .icon-inbox:before { content: "\e63a"; } .icon-download:before { content: "\e63b"; } .icon-upload:before { content: "\e63c"; } .icon-inbox2:before { content: "\e63d"; } .icon-checkmark:before { content: "\e63e"; } .icon-checkmark2:before { content: "\e63f"; } .icon-cancel:before { content: "\e640"; } .icon-cancel2:before { content: "\e641"; } .icon-plus:before { content: "\e642"; } .icon-plus2:before { content: "\e643"; } .icon-minus:before { content: "\e644"; } .icon-minus2:before { content: "\e645"; } .icon-notice:before { content: "\e646"; } .icon-notice2:before { content: "\e647"; } .icon-cog:before { content: "\e648"; } .icon-cogs:before { content: "\e649"; } .icon-cog2:before { content: "\e64a"; } .icon-warning:before { content: "\e64b"; } .icon-health:before { content: "\e64c"; } .icon-suitcase:before { content: "\e64d"; } .icon-suitcase2:before { content: "\e64e"; } .icon-suitcase3:before { content: "\e64f"; } .icon-picture:before { content: "\e650"; } .icon-pictures:before { content: "\e651"; } .icon-pictures2:before { content: "\e652"; } .icon-android:before { content: "\e653"; } .icon-marvin:before { content: "\e654"; } .icon-pacman:before { content: "\e655"; } .icon-cassette:before { content: "\e656"; } .icon-watch:before { content: "\e657"; } .icon-chronometer:before { content: "\e658"; } .icon-watch2:before { content: "\e659"; } .icon-alarm-clock:before { content: "\e65a"; } .icon-time:before { content: "\e65b"; } .icon-time2:before { content: "\e65c"; } .icon-headphones:before { content: "\e65d"; } .icon-wallet:before { content: "\e65e"; } .icon-checkmark3:before { content: "\e65f"; } .icon-cancel3:before { content: "\e660"; } .icon-eye:before { content: "\e661"; } .icon-position:before { content: "\e662"; } .icon-site-map:before { content: "\e663"; } .icon-site-map2:before { content: "\e664"; } .icon-cloud:before { content: "\e665"; } .icon-upload2:before { content: "\e666"; } .icon-chart:before { content: "\e667"; } .icon-chart2:before { content: "\e668"; } .icon-chart3:before { content: "\e669"; } .icon-chart4:before { content: "\e66a"; } .icon-chart5:before { content: "\e66b"; } .icon-chart6:before { content: "\e66c"; } .icon-location:before { content: "\e66d"; } .icon-download2:before { content: "\e66e"; } .icon-basket:before { content: "\e66f"; } .icon-folder:before { content: "\e670"; } .icon-gamepad:before { content: "\e671"; } .icon-alarm:before { content: "\e672"; } .icon-alarm-cancel:before { content: "\e673"; } .icon-phone2:before { content: "\e674"; } .icon-phone3:before { content: "\e675"; } .icon-image:before { content: "\e676"; } .icon-open:before { content: "\e677"; } .icon-sale:before { content: "\e678"; } .icon-direction:before { content: "\e679"; } .icon-map:before { content: "\e67a"; } .icon-trashcan:before { content: "\e67b"; } .icon-vote:before { content: "\e67c"; } .icon-graduate:before { content: "\e67d"; } .icon-lab:before { content: "\e67e"; } .icon-tie:before { content: "\e67f"; } .icon-football:before { content: "\e680"; } .icon-eight-ball:before { content: "\e681"; } .icon-bowling:before { content: "\e682"; } .icon-bowling-pin:before { content: "\e683"; } .icon-baseball:before { content: "\e684"; } .icon-soccer:before { content: "\e685"; } .icon-3d-glasses:before { content: "\e686"; } .icon-microwave:before { content: "\e687"; } .icon-refrigerator:before { content: "\e688"; } .icon-oven:before { content: "\e689"; } .icon-washing-machine:before { content: "\e68a"; } .icon-mouse:before { content: "\e68b"; } .icon-smiley:before { content: "\e68c"; } .icon-sad:before { content: "\e68d"; } .icon-mute:before { content: "\e68e"; } .icon-hand:before { content: "\e68f"; } .icon-radio:before { content: "\e690"; } .icon-satellite:before { content: "\e691"; } .icon-medal:before { content: "\e692"; } .icon-medal2:before { content: "\e693"; } .icon-switch:before { content: "\e694"; } .icon-key:before { content: "\e695"; } .icon-cord:before { content: "\e696"; } .icon-locked:before { content: "\e697"; } .icon-unlocked:before { content: "\e698"; } .icon-locked2:before { content: "\e699"; } .icon-unlocked2:before { content: "\e69a"; } .icon-magnifier:before { content: "\e69b"; } .icon-zoom-in:before { content: "\e69c"; } .icon-zoom-out:before { content: "\e69d"; } .icon-stack:before { content: "\e69e"; } .icon-stack2:before { content: "\e69f"; } .icon-stack3:before { content: "\e6a0"; } .icon-david-star:before { content: "\e6a1"; } .icon-cross:before { content: "\e6a2"; } .icon-moon-andstar:before { content: "\e6a3"; } .icon-transformers:before { content: "\e6a4"; } .icon-batman:before { content: "\e6a5"; } .icon-space-invaders:before { content: "\e6a6"; } .icon-skeletor:before { content: "\e6a7"; } .icon-lamp:before { content: "\e6a8"; } .icon-lamp2:before { content: "\e6a9"; } .icon-umbrella:before { content: "\e6aa"; } .icon-street-light:before { content: "\e6ab"; } .icon-bomb:before { content: "\e6ac"; } .icon-archive:before { content: "\e6ad"; } .icon-battery:before { content: "\e6ae"; } .icon-battery2:before { content: "\e6af"; } .icon-battery3:before { content: "\e6b0"; } .icon-battery4:before { content: "\e6b1"; } .icon-battery5:before { content: "\e6b2"; } .icon-megaphone:before { content: "\e6b3"; } .icon-megaphone2:before { content: "\e6b4"; } .icon-patch:before { content: "\e6b5"; } .icon-pil:before { content: "\e6b6"; } .icon-injection:before { content: "\e6b7"; } .icon-thermometer:before { content: "\e6b8"; } .icon-lamp3:before { content: "\e6b9"; } .icon-lamp4:before { content: "\e6ba"; } .icon-lamp5:before { content: "\e6bb"; } .icon-cube:before { content: "\e6bc"; } .icon-box:before { content: "\e6bd"; } .icon-box2:before { content: "\e6be"; } .icon-diamond:before { content: "\e6bf"; } .icon-bag:before { content: "\e6c0"; } .icon-money-bag:before { content: "\e6c1"; } .icon-grid:before { content: "\e6c2"; } .icon-grid2:before { content: "\e6c3"; } .icon-list:before { content: "\e6c4"; } .icon-list2:before { content: "\e6c5"; } .icon-ruler:before { content: "\e6c6"; } .icon-ruler2:before { content: "\e6c7"; } .icon-layout:before { content: "\e6c8"; } .icon-layout2:before { content: "\e6c9"; } .icon-layout3:before { content: "\e6ca"; } .icon-layout4:before { content: "\e6cb"; } .icon-layout5:before { content: "\e6cc"; } .icon-layout6:before { content: "\e6cd"; } .icon-layout7:before { content: "\e6ce"; } .icon-layout8:before { content: "\e6cf"; } .icon-layout9:before { content: "\e6d0"; } .icon-layout10:before { content: "\e6d1"; } .icon-layout11:before { content: "\e6d2"; } .icon-layout12:before { content: "\e6d3"; } .icon-layout13:before { content: "\e6d4"; } .icon-layout14:before { content: "\e6d5"; } .icon-tools:before { content: "\e6d6"; } .icon-screwdriver:before { content: "\e6d7"; } .icon-paint:before { content: "\e6d8"; } .icon-hammer:before { content: "\e6d9"; } .icon-brush:before { content: "\e6da"; } .icon-pen:before { content: "\e6db"; } .icon-chat:before { content: "\e6dc"; } .icon-comments:before { content: "\e6dd"; } .icon-chat2:before { content: "\e6de"; } .icon-chat3:before { content: "\e6df"; } .icon-volume:before { content: "\e6e0"; } .icon-volume2:before { content: "\e6e1"; } .icon-volume3:before { content: "\e6e2"; } .icon-equalizer:before { content: "\e6e3"; } .icon-resize:before { content: "\e6e4"; } .icon-resize2:before { content: "\e6e5"; } .icon-stretch:before { content: "\e6e6"; } .icon-narrow:before { content: "\e6e7"; } .icon-resize3:before { content: "\e6e8"; } .icon-download3:before { content: "\e6e9"; } .icon-calculator:before { content: "\e6ea"; } .icon-library:before { content: "\e6eb"; } .icon-auction:before { content: "\e6ec"; } .icon-justice:before { content: "\e6ed"; } .icon-stats:before { content: "\e6ee"; } .icon-stats2:before { content: "\e6ef"; } .icon-attachment:before { content: "\e6f0"; } .icon-hourglass:before { content: "\e6f1"; } .icon-abacus:before { content: "\e6f2"; } .icon-pencil:before { content: "\e6f3"; } .icon-pen2:before { content: "\e6f4"; } .icon-pin:before { content: "\e6f5"; } .icon-pin2:before { content: "\e6f6"; } .icon-discout:before { content: "\e6f7"; } .icon-edit:before { content: "\e6f8"; } .icon-scissors:before { content: "\e6f9"; } .icon-profile:before { content: "\e6fa"; } .icon-profile2:before { content: "\e6fb"; } .icon-profile3:before { content: "\e6fc"; } .icon-rotate:before { content: "\e6fd"; } .icon-rotate2:before { content: "\e6fe"; } .icon-reply:before { content: "\e6ff"; } .icon-forward:before { content: "\e700"; } .icon-retweet:before { content: "\e701"; } .icon-shuffle:before { content: "\e702"; } .icon-loop:before { content: "\e703"; } .icon-crop:before { content: "\e704"; } .icon-square:before { content: "\e705"; } .icon-square2:before { content: "\e706"; } .icon-circle:before { content: "\e707"; } .icon-dollar:before { content: "\e708"; } .icon-dollar2:before { content: "\e709"; } .icon-coins:before { content: "\e70a"; } .icon-pig:before { content: "\e70b"; } .icon-bookmark:before { content: "\e70c"; } .icon-bookmark2:before { content: "\e70d"; } .icon-address-book:before { content: "\e70e"; } .icon-address-book2:before { content: "\e70f"; } .icon-safe:before { content: "\e710"; } .icon-envelope:before { content: "\e711"; } .icon-envelope2:before { content: "\e712"; } .icon-radio-active:before { content: "\e713"; } .icon-music:before { content: "\e714"; } .icon-presentation:before { content: "\e715"; } .icon-male:before { content: "\e716"; } .icon-female:before { content: "\e717"; } .icon-aids:before { content: "\e718"; } .icon-heart:before { content: "\e719"; } .icon-info:before { content: "\e71a"; } .icon-info2:before { content: "\e71b"; } .icon-piano:before { content: "\e71c"; } .icon-rain:before { content: "\e71d"; } .icon-snow:before { content: "\e71e"; } .icon-lightning:before { content: "\e71f"; } .icon-sun:before { content: "\e720"; } .icon-moon:before { content: "\e721"; } .icon-cloudy:before { content: "\e722"; } .icon-cloudy2:before { content: "\e723"; } .icon-car:before { content: "\e724"; } .icon-bike:before { content: "\e725"; } .icon-truck:before { content: "\e726"; } .icon-bus:before { content: "\e727"; } .icon-bike2:before { content: "\e728"; } .icon-plane:before { content: "\e729"; } .icon-paper-plane:before { content: "\e72a"; } .icon-rocket:before { content: "\e72b"; } .icon-book:before { content: "\e72c"; } .icon-book2:before { content: "\e72d"; } .icon-barcode:before { content: "\e72e"; } .icon-barcode2:before { content: "\e72f"; } .icon-expand:before { content: "\e730"; } .icon-collapse:before { content: "\e731"; } .icon-pop-out:before { content: "\e732"; } .icon-pop-in:before { content: "\e733"; } .icon-target:before { content: "\e734"; } .icon-badge:before { content: "\e735"; } .icon-badge2:before { content: "\e736"; } .icon-ticket:before { content: "\e737"; } .icon-ticket2:before { content: "\e738"; } .icon-ticket3:before { content: "\e739"; } .icon-microphone4:before { content: "\e73a"; } .icon-cone:before { content: "\e73b"; } .icon-blocked:before { content: "\e73c"; } .icon-stop:before { content: "\e73d"; } .icon-keyboard:before { content: "\e73e"; } .icon-keyboard2:before { content: "\e73f"; } .icon-radio2:before { content: "\e740"; } .icon-printer:before { content: "\e741"; } .icon-checked:before { content: "\e742"; } .icon-error:before { content: "\e743"; } .icon-add:before { content: "\e744"; } .icon-minus3:before { content: "\e745"; } .icon-alert:before { content: "\e746"; } .icon-pictures3:before { content: "\e747"; } .icon-atom:before { content: "\e748"; } .icon-eyedropper:before { content: "\e749"; } .icon-globe:before { content: "\e74a"; } .icon-globe2:before { content: "\e74b"; } .icon-shipping:before { content: "\e74c"; } .icon-ying-yang:before { content: "\e74d"; } .icon-compass:before { content: "\e74e"; } .icon-zip:before { content: "\e74f"; } .icon-zip2:before { content: "\e750"; } .icon-anchor:before { content: "\e751"; } .icon-locked-heart:before { content: "\e752"; } .icon-magnet:before { content: "\e753"; } .icon-navigation:before { content: "\e754"; } .icon-tags:before { content: "\e755"; } .icon-heart2:before { content: "\e756"; } .icon-heart3:before { content: "\e757"; } .icon-usb:before { content: "\e758"; } .icon-clipboard:before { content: "\e759"; } .icon-clipboard2:before { content: "\e75a"; } .icon-clipboard3:before { content: "\e75b"; } .icon-switch2:before { content: "\e75c"; } .icon-ruler3:before { content: "\e75d"; } /* Animate.css - http://daneden.me/animate Licensed under the MIT license Copyright (c) 2013 Daniel Eden 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. */ .animated { -webkit-animation-duration: 1s; animation-duration: 1s; -webkit-animation-fill-mode: both; animation-fill-mode: both; } .animated.hinge { -webkit-animation-duration: 2s; animation-duration: 2s; } @-webkit-keyframes bounce { 0%, 20%, 50%, 80%, 100% { -webkit-transform: translateY(0); transform: translateY(0); } 40% { -webkit-transform: translateY(-30px); transform: translateY(-30px); } 60% { -webkit-transform: translateY(-15px); transform: translateY(-15px); } } @keyframes bounce { 0%, 20%, 50%, 80%, 100% { -webkit-transform: translateY(0); -ms-transform: translateY(0); transform: translateY(0); } 40% { -webkit-transform: translateY(-30px); -ms-transform: translateY(-30px); transform: translateY(-30px); } 60% { -webkit-transform: translateY(-15px); -ms-transform: translateY(-15px); transform: translateY(-15px); } } .bounce { -webkit-animation-name: bounce; animation-name: bounce; } @-webkit-keyframes flash { 0%, 50%, 100% { opacity: 1; } 25%, 75% { opacity: 0; } } @keyframes flash { 0%, 50%, 100% { opacity: 1; } 25%, 75% { opacity: 0; } } .flash { -webkit-animation-name: flash; animation-name: flash; } /* originally authored by Nick Pettit - https://github.com/nickpettit/glide */ @-webkit-keyframes pulse { 0% { -webkit-transform: scale(1); transform: scale(1); } 50% { -webkit-transform: scale(1.1); transform: scale(1.1); } 100% { -webkit-transform: scale(1); transform: scale(1); } } @keyframes pulse { 0% { -webkit-transform: scale(1); -ms-transform: scale(1); transform: scale(1); } 50% { -webkit-transform: scale(1.1); -ms-transform: scale(1.1); transform: scale(1.1); } 100% { -webkit-transform: scale(1); -ms-transform: scale(1); transform: scale(1); } } .pulse { -webkit-animation-name: pulse; animation-name: pulse; } @-webkit-keyframes shake { 0%, 100% { -webkit-transform: translateX(0); transform: translateX(0); } 10%, 30%, 50%, 70%, 90% { -webkit-transform: translateX(-10px); transform: translateX(-10px); } 20%, 40%, 60%, 80% { -webkit-transform: translateX(10px); transform: translateX(10px); } } @keyframes shake { 0%, 100% { -webkit-transform: translateX(0); -ms-transform: translateX(0); transform: translateX(0); } 10%, 30%, 50%, 70%, 90% { -webkit-transform: translateX(-10px); -ms-transform: translateX(-10px); transform: translateX(-10px); } 20%, 40%, 60%, 80% { -webkit-transform: translateX(10px); -ms-transform: translateX(10px); transform: translateX(10px); } } .shake { -webkit-animation-name: shake; animation-name: shake; } @-webkit-keyframes swing { 20% { -webkit-transform: rotate(15deg); transform: rotate(15deg); } 40% { -webkit-transform: rotate(-10deg); transform: rotate(-10deg); } 60% { -webkit-transform: rotate(5deg); transform: rotate(5deg); } 80% { -webkit-transform: rotate(-5deg); transform: rotate(-5deg); } 100% { -webkit-transform: rotate(0deg); transform: rotate(0deg); } } @keyframes swing { 20% { -webkit-transform: rotate(15deg); -ms-transform: rotate(15deg); transform: rotate(15deg); } 40% { -webkit-transform: rotate(-10deg); -ms-transform: rotate(-10deg); transform: rotate(-10deg); } 60% { -webkit-transform: rotate(5deg); -ms-transform: rotate(5deg); transform: rotate(5deg); } 80% { -webkit-transform: rotate(-5deg); -ms-transform: rotate(-5deg); transform: rotate(-5deg); } 100% { -webkit-transform: rotate(0deg); -ms-transform: rotate(0deg); transform: rotate(0deg); } } .swing { -webkit-transform-origin: top center; -ms-transform-origin: top center; transform-origin: top center; -webkit-animation-name: swing; animation-name: swing; } @-webkit-keyframes tada { 0% { -webkit-transform: scale(1); transform: scale(1); } 10%, 20% { -webkit-transform: scale(0.9) rotate(-3deg); transform: scale(0.9) rotate(-3deg); } 30%, 50%, 70%, 90% { -webkit-transform: scale(1.1) rotate(3deg); transform: scale(1.1) rotate(3deg); } 40%, 60%, 80% { -webkit-transform: scale(1.1) rotate(-3deg); transform: scale(1.1) rotate(-3deg); } 100% { -webkit-transform: scale(1) rotate(0); transform: scale(1) rotate(0); } } @keyframes tada { 0% { -webkit-transform: scale(1); -ms-transform: scale(1); transform: scale(1); } 10%, 20% { -webkit-transform: scale(0.9) rotate(-3deg); -ms-transform: scale(0.9) rotate(-3deg); transform: scale(0.9) rotate(-3deg); } 30%, 50%, 70%, 90% { -webkit-transform: scale(1.1) rotate(3deg); -ms-transform: scale(1.1) rotate(3deg); transform: scale(1.1) rotate(3deg); } 40%, 60%, 80% { -webkit-transform: scale(1.1) rotate(-3deg); -ms-transform: scale(1.1) rotate(-3deg); transform: scale(1.1) rotate(-3deg); } 100% { -webkit-transform: scale(1) rotate(0); -ms-transform: scale(1) rotate(0); transform: scale(1) rotate(0); } } .tada { -webkit-animation-name: tada; animation-name: tada; } /* originally authored by Nick Pettit - https://github.com/nickpettit/glide */ @-webkit-keyframes wobble { 0% { -webkit-transform: translateX(0%); transform: translateX(0%); } 15% { -webkit-transform: translateX(-25%) rotate(-5deg); transform: translateX(-25%) rotate(-5deg); } 30% { -webkit-transform: translateX(20%) rotate(3deg); transform: translateX(20%) rotate(3deg); } 45% { -webkit-transform: translateX(-15%) rotate(-3deg); transform: translateX(-15%) rotate(-3deg); } 60% { -webkit-transform: translateX(10%) rotate(2deg); transform: translateX(10%) rotate(2deg); } 75% { -webkit-transform: translateX(-5%) rotate(-1deg); transform: translateX(-5%) rotate(-1deg); } 100% { -webkit-transform: translateX(0%); transform: translateX(0%); } } @keyframes wobble { 0% { -webkit-transform: translateX(0%); -ms-transform: translateX(0%); transform: translateX(0%); } 15% { -webkit-transform: translateX(-25%) rotate(-5deg); -ms-transform: translateX(-25%) rotate(-5deg); transform: translateX(-25%) rotate(-5deg); } 30% { -webkit-transform: translateX(20%) rotate(3deg); -ms-transform: translateX(20%) rotate(3deg); transform: translateX(20%) rotate(3deg); } 45% { -webkit-transform: translateX(-15%) rotate(-3deg); -ms-transform: translateX(-15%) rotate(-3deg); transform: translateX(-15%) rotate(-3deg); } 60% { -webkit-transform: translateX(10%) rotate(2deg); -ms-transform: translateX(10%) rotate(2deg); transform: translateX(10%) rotate(2deg); } 75% { -webkit-transform: translateX(-5%) rotate(-1deg); -ms-transform: translateX(-5%) rotate(-1deg); transform: translateX(-5%) rotate(-1deg); } 100% { -webkit-transform: translateX(0%); -ms-transform: translateX(0%); transform: translateX(0%); } } .wobble { -webkit-animation-name: wobble; animation-name: wobble; } @-webkit-keyframes bounceIn { 0% { opacity: 0; -webkit-transform: scale(0.3); transform: scale(0.3); } 50% { opacity: 1; -webkit-transform: scale(1.05); transform: scale(1.05); } 70% { -webkit-transform: scale(0.9); transform: scale(0.9); } 100% { -webkit-transform: scale(1); transform: scale(1); } } @keyframes bounceIn { 0% { opacity: 0; -webkit-transform: scale(0.3); -ms-transform: scale(0.3); transform: scale(0.3); } 50% { opacity: 1; -webkit-transform: scale(1.05); -ms-transform: scale(1.05); transform: scale(1.05); } 70% { -webkit-transform: scale(0.9); -ms-transform: scale(0.9); transform: scale(0.9); } 100% { -webkit-transform: scale(1); -ms-transform: scale(1); transform: scale(1); } } .bounceIn { -webkit-animation-name: bounceIn; animation-name: bounceIn; } @-webkit-keyframes bounceInDown { 0% { opacity: 0; -webkit-transform: translateY(-2000px); transform: translateY(-2000px); } 60% { opacity: 1; -webkit-transform: translateY(30px); transform: translateY(30px); } 80% { -webkit-transform: translateY(-10px); transform: translateY(-10px); } 100% { -webkit-transform: translateY(0); transform: translateY(0); } } @keyframes bounceInDown { 0% { opacity: 0; -webkit-transform: translateY(-2000px); -ms-transform: translateY(-2000px); transform: translateY(-2000px); } 60% { opacity: 1; -webkit-transform: translateY(30px); -ms-transform: translateY(30px); transform: translateY(30px); } 80% { -webkit-transform: translateY(-10px); -ms-transform: translateY(-10px); transform: translateY(-10px); } 100% { -webkit-transform: translateY(0); -ms-transform: translateY(0); transform: translateY(0); } } .bounceInDown { -webkit-animation-name: bounceInDown; animation-name: bounceInDown; } @-webkit-keyframes bounceInLeft { 0% { opacity: 0; -webkit-transform: translateX(-2000px); transform: translateX(-2000px); } 60% { opacity: 1; -webkit-transform: translateX(30px); transform: translateX(30px); } 80% { -webkit-transform: translateX(-10px); transform: translateX(-10px); } 100% { -webkit-transform: translateX(0); transform: translateX(0); } } @keyframes bounceInLeft { 0% { opacity: 0; -webkit-transform: translateX(-2000px); -ms-transform: translateX(-2000px); transform: translateX(-2000px); } 60% { opacity: 1; -webkit-transform: translateX(30px); -ms-transform: translateX(30px); transform: translateX(30px); } 80% { -webkit-transform: translateX(-10px); -ms-transform: translateX(-10px); transform: translateX(-10px); } 100% { -webkit-transform: translateX(0); -ms-transform: translateX(0); transform: translateX(0); } } .bounceInLeft { -webkit-animation-name: bounceInLeft; animation-name: bounceInLeft; } @-webkit-keyframes bounceInRight { 0% { opacity: 0; -webkit-transform: translateX(2000px); transform: translateX(2000px); } 60% { opacity: 1; -webkit-transform: translateX(-30px); transform: translateX(-30px); } 80% { -webkit-transform: translateX(10px); transform: translateX(10px); } 100% { -webkit-transform: translateX(0); transform: translateX(0); } } @keyframes bounceInRight { 0% { opacity: 0; -webkit-transform: translateX(2000px); -ms-transform: translateX(2000px); transform: translateX(2000px); } 60% { opacity: 1; -webkit-transform: translateX(-30px); -ms-transform: translateX(-30px); transform: translateX(-30px); } 80% { -webkit-transform: translateX(10px); -ms-transform: translateX(10px); transform: translateX(10px); } 100% { -webkit-transform: translateX(0); -ms-transform: translateX(0); transform: translateX(0); } } .bounceInRight { -webkit-animation-name: bounceInRight; animation-name: bounceInRight; } @-webkit-keyframes bounceInUp { 0% { opacity: 0; -webkit-transform: translateY(2000px); transform: translateY(2000px); } 60% { opacity: 1; -webkit-transform: translateY(-30px); transform: translateY(-30px); } 80% { -webkit-transform: translateY(10px); transform: translateY(10px); } 100% { -webkit-transform: translateY(0); transform: translateY(0); } } @keyframes bounceInUp { 0% { opacity: 0; -webkit-transform: translateY(2000px); -ms-transform: translateY(2000px); transform: translateY(2000px); } 60% { opacity: 1; -webkit-transform: translateY(-30px); -ms-transform: translateY(-30px); transform: translateY(-30px); } 80% { -webkit-transform: translateY(10px); -ms-transform: translateY(10px); transform: translateY(10px); } 100% { -webkit-transform: translateY(0); -ms-transform: translateY(0); transform: translateY(0); } } .bounceInUp { -webkit-animation-name: bounceInUp; animation-name: bounceInUp; } @-webkit-keyframes bounceOut { 0% { -webkit-transform: scale(1); transform: scale(1); } 25% { -webkit-transform: scale(0.95); transform: scale(0.95); } 50% { opacity: 1; -webkit-transform: scale(1.1); transform: scale(1.1); } 100% { opacity: 0; -webkit-transform: scale(0.3); transform: scale(0.3); } } @keyframes bounceOut { 0% { -webkit-transform: scale(1); -ms-transform: scale(1); transform: scale(1); } 25% { -webkit-transform: scale(0.95); -ms-transform: scale(0.95); transform: scale(0.95); } 50% { opacity: 1; -webkit-transform: scale(1.1); -ms-transform: scale(1.1); transform: scale(1.1); } 100% { opacity: 0; -webkit-transform: scale(0.3); -ms-transform: scale(0.3); transform: scale(0.3); } } .bounceOut { -webkit-animation-name: bounceOut; animation-name: bounceOut; } @-webkit-keyframes bounceOutDown { 0% { -webkit-transform: translateY(0); transform: translateY(0); } 20% { opacity: 1; -webkit-transform: translateY(-20px); transform: translateY(-20px); } 100% { opacity: 0; -webkit-transform: translateY(2000px); transform: translateY(2000px); } } @keyframes bounceOutDown { 0% { -webkit-transform: translateY(0); -ms-transform: translateY(0); transform: translateY(0); } 20% { opacity: 1; -webkit-transform: translateY(-20px); -ms-transform: translateY(-20px); transform: translateY(-20px); } 100% { opacity: 0; -webkit-transform: translateY(2000px); -ms-transform: translateY(2000px); transform: translateY(2000px); } } .bounceOutDown { -webkit-animation-name: bounceOutDown; animation-name: bounceOutDown; } @-webkit-keyframes bounceOutLeft { 0% { -webkit-transform: translateX(0); transform: translateX(0); } 20% { opacity: 1; -webkit-transform: translateX(20px); transform: translateX(20px); } 100% { opacity: 0; -webkit-transform: translateX(-2000px); transform: translateX(-2000px); } } @keyframes bounceOutLeft { 0% { -webkit-transform: translateX(0); -ms-transform: translateX(0); transform: translateX(0); } 20% { opacity: 1; -webkit-transform: translateX(20px); -ms-transform: translateX(20px); transform: translateX(20px); } 100% { opacity: 0; -webkit-transform: translateX(-2000px); -ms-transform: translateX(-2000px); transform: translateX(-2000px); } } .bounceOutLeft { -webkit-animation-name: bounceOutLeft; animation-name: bounceOutLeft; } @-webkit-keyframes bounceOutRight { 0% { -webkit-transform: translateX(0); transform: translateX(0); } 20% { opacity: 1; -webkit-transform: translateX(-20px); transform: translateX(-20px); } 100% { opacity: 0; -webkit-transform: translateX(2000px); transform: translateX(2000px); } } @keyframes bounceOutRight { 0% { -webkit-transform: translateX(0); -ms-transform: translateX(0); transform: translateX(0); } 20% { opacity: 1; -webkit-transform: translateX(-20px); -ms-transform: translateX(-20px); transform: translateX(-20px); } 100% { opacity: 0; -webkit-transform: translateX(2000px); -ms-transform: translateX(2000px); transform: translateX(2000px); } } .bounceOutRight { -webkit-animation-name: bounceOutRight; animation-name: bounceOutRight; } @-webkit-keyframes bounceOutUp { 0% { -webkit-transform: translateY(0); transform: translateY(0); } 20% { opacity: 1; -webkit-transform: translateY(20px); transform: translateY(20px); } 100% { opacity: 0; -webkit-transform: translateY(-2000px); transform: translateY(-2000px); } } @keyframes bounceOutUp { 0% { -webkit-transform: translateY(0); -ms-transform: translateY(0); transform: translateY(0); } 20% { opacity: 1; -webkit-transform: translateY(20px); -ms-transform: translateY(20px); transform: translateY(20px); } 100% { opacity: 0; -webkit-transform: translateY(-2000px); -ms-transform: translateY(-2000px); transform: translateY(-2000px); } } .bounceOutUp { -webkit-animation-name: bounceOutUp; animation-name: bounceOutUp; } @-webkit-keyframes fadeIn { 0% { opacity: 0; } 100% { opacity: 1; } } @keyframes fadeIn { 0% { opacity: 0; } 100% { opacity: 1; } } .fadeIn { -webkit-animation-name: fadeIn; animation-name: fadeIn; } @-webkit-keyframes fadeInDown { 0% { opacity: 0; -webkit-transform: translateY(-20px); transform: translateY(-20px); } 100% { opacity: 1; -webkit-transform: translateY(0); transform: translateY(0); } } @keyframes fadeInDown { 0% { opacity: 0; -webkit-transform: translateY(-20px); -ms-transform: translateY(-20px); transform: translateY(-20px); } 100% { opacity: 1; -webkit-transform: translateY(0); -ms-transform: translateY(0); transform: translateY(0); } } .fadeInDown { -webkit-animation-name: fadeInDown; animation-name: fadeInDown; } @-webkit-keyframes fadeInDownBig { 0% { opacity: 0; -webkit-transform: translateY(-2000px); transform: translateY(-2000px); } 100% { opacity: 1; -webkit-transform: translateY(0); transform: translateY(0); } } @keyframes fadeInDownBig { 0% { opacity: 0; -webkit-transform: translateY(-2000px); -ms-transform: translateY(-2000px); transform: translateY(-2000px); } 100% { opacity: 1; -webkit-transform: translateY(0); -ms-transform: translateY(0); transform: translateY(0); } } .fadeInDownBig { -webkit-animation-name: fadeInDownBig; animation-name: fadeInDownBig; } @-webkit-keyframes fadeInLeft { 0% { opacity: 0; -webkit-transform: translateX(-20px); transform: translateX(-20px); } 100% { opacity: 1; -webkit-transform: translateX(0); transform: translateX(0); } } @keyframes fadeInLeft { 0% { opacity: 0; -webkit-transform: translateX(-20px); -ms-transform: translateX(-20px); transform: translateX(-20px); } 100% { opacity: 1; -webkit-transform: translateX(0); -ms-transform: translateX(0); transform: translateX(0); } } .fadeInLeft { -webkit-animation-name: fadeInLeft; animation-name: fadeInLeft; } @-webkit-keyframes fadeInLeftBig { 0% { opacity: 0; -webkit-transform: translateX(-2000px); transform: translateX(-2000px); } 100% { opacity: 1; -webkit-transform: translateX(0); transform: translateX(0); } } @keyframes fadeInLeftBig { 0% { opacity: 0; -webkit-transform: translateX(-2000px); -ms-transform: translateX(-2000px); transform: translateX(-2000px); } 100% { opacity: 1; -webkit-transform: translateX(0); -ms-transform: translateX(0); transform: translateX(0); } } .fadeInLeftBig { -webkit-animation-name: fadeInLeftBig; animation-name: fadeInLeftBig; } @-webkit-keyframes fadeInRight { 0% { opacity: 0; -webkit-transform: translateX(20px); transform: translateX(20px); } 100% { opacity: 1; -webkit-transform: translateX(0); transform: translateX(0); } } @keyframes fadeInRight { 0% { opacity: 0; -webkit-transform: translateX(20px); -ms-transform: translateX(20px); transform: translateX(20px); } 100% { opacity: 1; -webkit-transform: translateX(0); -ms-transform: translateX(0); transform: translateX(0); } } .fadeInRight { -webkit-animation-name: fadeInRight; animation-name: fadeInRight; } @-webkit-keyframes fadeInRightBig { 0% { opacity: 0; -webkit-transform: translateX(2000px); transform: translateX(2000px); } 100% { opacity: 1; -webkit-transform: translateX(0); transform: translateX(0); } } @keyframes fadeInRightBig { 0% { opacity: 0; -webkit-transform: translateX(2000px); -ms-transform: translateX(2000px); transform: translateX(2000px); } 100% { opacity: 1; -webkit-transform: translateX(0); -ms-transform: translateX(0); transform: translateX(0); } } .fadeInRightBig { -webkit-animation-name: fadeInRightBig; animation-name: fadeInRightBig; } @-webkit-keyframes fadeInUp { 0% { opacity: 0; -webkit-transform: translateY(20px); transform: translateY(20px); } 100% { opacity: 1; -webkit-transform: translateY(0); transform: translateY(0); } } @keyframes fadeInUp { 0% { opacity: 0; -webkit-transform: translateY(20px); -ms-transform: translateY(20px); transform: translateY(20px); } 100% { opacity: 1; -webkit-transform: translateY(0); -ms-transform: translateY(0); transform: translateY(0); } } .fadeInUp { -webkit-animation-name: fadeInUp; animation-name: fadeInUp; } @-webkit-keyframes fadeInUpBig { 0% { opacity: 0; -webkit-transform: translateY(2000px); transform: translateY(2000px); } 100% { opacity: 1; -webkit-transform: translateY(0); transform: translateY(0); } } @keyframes fadeInUpBig { 0% { opacity: 0; -webkit-transform: translateY(2000px); -ms-transform: translateY(2000px); transform: translateY(2000px); } 100% { opacity: 1; -webkit-transform: translateY(0); -ms-transform: translateY(0); transform: translateY(0); } } .fadeInUpBig { -webkit-animation-name: fadeInUpBig; animation-name: fadeInUpBig; } @-webkit-keyframes fadeOut { 0% { opacity: 1; } 100% { opacity: 0; } } @keyframes fadeOut { 0% { opacity: 1; } 100% { opacity: 0; } } .fadeOut { -webkit-animation-name: fadeOut; animation-name: fadeOut; } @-webkit-keyframes fadeOutDown { 0% { opacity: 1; -webkit-transform: translateY(0); transform: translateY(0); } 100% { opacity: 0; -webkit-transform: translateY(20px); transform: translateY(20px); } } @keyframes fadeOutDown { 0% { opacity: 1; -webkit-transform: translateY(0); -ms-transform: translateY(0); transform: translateY(0); } 100% { opacity: 0; -webkit-transform: translateY(20px); -ms-transform: translateY(20px); transform: translateY(20px); } } .fadeOutDown { -webkit-animation-name: fadeOutDown; animation-name: fadeOutDown; } @-webkit-keyframes fadeOutDownBig { 0% { opacity: 1; -webkit-transform: translateY(0); transform: translateY(0); } 100% { opacity: 0; -webkit-transform: translateY(2000px); transform: translateY(2000px); } } @keyframes fadeOutDownBig { 0% { opacity: 1; -webkit-transform: translateY(0); -ms-transform: translateY(0); transform: translateY(0); } 100% { opacity: 0; -webkit-transform: translateY(2000px); -ms-transform: translateY(2000px); transform: translateY(2000px); } } .fadeOutDownBig { -webkit-animation-name: fadeOutDownBig; animation-name: fadeOutDownBig; } @-webkit-keyframes fadeOutLeft { 0% { opacity: 1; -webkit-transform: translateX(0); transform: translateX(0); } 100% { opacity: 0; -webkit-transform: translateX(-20px); transform: translateX(-20px); } } @keyframes fadeOutLeft { 0% { opacity: 1; -webkit-transform: translateX(0); -ms-transform: translateX(0); transform: translateX(0); } 100% { opacity: 0; -webkit-transform: translateX(-20px); -ms-transform: translateX(-20px); transform: translateX(-20px); } } .fadeOutLeft { -webkit-animation-name: fadeOutLeft; animation-name: fadeOutLeft; } @-webkit-keyframes fadeOutLeftBig { 0% { opacity: 1; -webkit-transform: translateX(0); transform: translateX(0); } 100% { opacity: 0; -webkit-transform: translateX(-2000px); transform: translateX(-2000px); } } @keyframes fadeOutLeftBig { 0% { opacity: 1; -webkit-transform: translateX(0); -ms-transform: translateX(0); transform: translateX(0); } 100% { opacity: 0; -webkit-transform: translateX(-2000px); -ms-transform: translateX(-2000px); transform: translateX(-2000px); } } .fadeOutLeftBig { -webkit-animation-name: fadeOutLeftBig; animation-name: fadeOutLeftBig; } @-webkit-keyframes fadeOutRight { 0% { opacity: 1; -webkit-transform: translateX(0); transform: translateX(0); } 100% { opacity: 0; -webkit-transform: translateX(20px); transform: translateX(20px); } } @keyframes fadeOutRight { 0% { opacity: 1; -webkit-transform: translateX(0); -ms-transform: translateX(0); transform: translateX(0); } 100% { opacity: 0; -webkit-transform: translateX(20px); -ms-transform: translateX(20px); transform: translateX(20px); } } .fadeOutRight { -webkit-animation-name: fadeOutRight; animation-name: fadeOutRight; } @-webkit-keyframes fadeOutRightBig { 0% { opacity: 1; -webkit-transform: translateX(0); transform: translateX(0); } 100% { opacity: 0; -webkit-transform: translateX(2000px); transform: translateX(2000px); } } @keyframes fadeOutRightBig { 0% { opacity: 1; -webkit-transform: translateX(0); -ms-transform: translateX(0); transform: translateX(0); } 100% { opacity: 0; -webkit-transform: translateX(2000px); -ms-transform: translateX(2000px); transform: translateX(2000px); } } .fadeOutRightBig { -webkit-animation-name: fadeOutRightBig; animation-name: fadeOutRightBig; } @-webkit-keyframes fadeOutUp { 0% { opacity: 1; -webkit-transform: translateY(0); transform: translateY(0); } 100% { opacity: 0; -webkit-transform: translateY(-20px); transform: translateY(-20px); } } @keyframes fadeOutUp { 0% { opacity: 1; -webkit-transform: translateY(0); -ms-transform: translateY(0); transform: translateY(0); } 100% { opacity: 0; -webkit-transform: translateY(-20px); -ms-transform: translateY(-20px); transform: translateY(-20px); } } .fadeOutUp { -webkit-animation-name: fadeOutUp; animation-name: fadeOutUp; } @-webkit-keyframes fadeOutUpBig { 0% { opacity: 1; -webkit-transform: translateY(0); transform: translateY(0); } 100% { opacity: 0; -webkit-transform: translateY(-2000px); transform: translateY(-2000px); } } @keyframes fadeOutUpBig { 0% { opacity: 1; -webkit-transform: translateY(0); -ms-transform: translateY(0); transform: translateY(0); } 100% { opacity: 0; -webkit-transform: translateY(-2000px); -ms-transform: translateY(-2000px); transform: translateY(-2000px); } } .fadeOutUpBig { -webkit-animation-name: fadeOutUpBig; animation-name: fadeOutUpBig; } @-webkit-keyframes flip { 0% { -webkit-transform: perspective(400px) translateZ(0) rotateY(0) scale(1); transform: perspective(400px) translateZ(0) rotateY(0) scale(1); -webkit-animation-timing-function: ease-out; animation-timing-function: ease-out; } 40% { -webkit-transform: perspective(400px) translateZ(150px) rotateY(170deg) scale(1); transform: perspective(400px) translateZ(150px) rotateY(170deg) scale(1); -webkit-animation-timing-function: ease-out; animation-timing-function: ease-out; } 50% { -webkit-transform: perspective(400px) translateZ(150px) rotateY(190deg) scale(1); transform: perspective(400px) translateZ(150px) rotateY(190deg) scale(1); -webkit-animation-timing-function: ease-in; animation-timing-function: ease-in; } 80% { -webkit-transform: perspective(400px) translateZ(0) rotateY(360deg) scale(0.95); transform: perspective(400px) translateZ(0) rotateY(360deg) scale(0.95); -webkit-animation-timing-function: ease-in; animation-timing-function: ease-in; } 100% { -webkit-transform: perspective(400px) translateZ(0) rotateY(360deg) scale(1); transform: perspective(400px) translateZ(0) rotateY(360deg) scale(1); -webkit-animation-timing-function: ease-in; animation-timing-function: ease-in; } } @keyframes flip { 0% { -webkit-transform: perspective(400px) translateZ(0) rotateY(0) scale(1); -ms-transform: perspective(400px) translateZ(0) rotateY(0) scale(1); transform: perspective(400px) translateZ(0) rotateY(0) scale(1); -webkit-animation-timing-function: ease-out; animation-timing-function: ease-out; } 40% { -webkit-transform: perspective(400px) translateZ(150px) rotateY(170deg) scale(1); -ms-transform: perspective(400px) translateZ(150px) rotateY(170deg) scale(1); transform: perspective(400px) translateZ(150px) rotateY(170deg) scale(1); -webkit-animation-timing-function: ease-out; animation-timing-function: ease-out; } 50% { -webkit-transform: perspective(400px) translateZ(150px) rotateY(190deg) scale(1); -ms-transform: perspective(400px) translateZ(150px) rotateY(190deg) scale(1); transform: perspective(400px) translateZ(150px) rotateY(190deg) scale(1); -webkit-animation-timing-function: ease-in; animation-timing-function: ease-in; } 80% { -webkit-transform: perspective(400px) translateZ(0) rotateY(360deg) scale(0.95); -ms-transform: perspective(400px) translateZ(0) rotateY(360deg) scale(0.95); transform: perspective(400px) translateZ(0) rotateY(360deg) scale(0.95); -webkit-animation-timing-function: ease-in; animation-timing-function: ease-in; } 100% { -webkit-transform: perspective(400px) translateZ(0) rotateY(360deg) scale(1); -ms-transform: perspective(400px) translateZ(0) rotateY(360deg) scale(1); transform: perspective(400px) translateZ(0) rotateY(360deg) scale(1); -webkit-animation-timing-function: ease-in; animation-timing-function: ease-in; } } .animated.flip { -webkit-backface-visibility: visible; -ms-backface-visibility: visible; backface-visibility: visible; -webkit-animation-name: flip; animation-name: flip; } @-webkit-keyframes flipInX { 0% { -webkit-transform: perspective(400px) rotateX(90deg); transform: perspective(400px) rotateX(90deg); opacity: 0; } 40% { -webkit-transform: perspective(400px) rotateX(-10deg); transform: perspective(400px) rotateX(-10deg); } 70% { -webkit-transform: perspective(400px) rotateX(10deg); transform: perspective(400px) rotateX(10deg); } 100% { -webkit-transform: perspective(400px) rotateX(0deg); transform: perspective(400px) rotateX(0deg); opacity: 1; } } @keyframes flipInX { 0% { -webkit-transform: perspective(400px) rotateX(90deg); -ms-transform: perspective(400px) rotateX(90deg); transform: perspective(400px) rotateX(90deg); opacity: 0; } 40% { -webkit-transform: perspective(400px) rotateX(-10deg); -ms-transform: perspective(400px) rotateX(-10deg); transform: perspective(400px) rotateX(-10deg); } 70% { -webkit-transform: perspective(400px) rotateX(10deg); -ms-transform: perspective(400px) rotateX(10deg); transform: perspective(400px) rotateX(10deg); } 100% { -webkit-transform: perspective(400px) rotateX(0deg); -ms-transform: perspective(400px) rotateX(0deg); transform: perspective(400px) rotateX(0deg); opacity: 1; } } .flipInX { -webkit-backface-visibility: visible !important; -ms-backface-visibility: visible !important; backface-visibility: visible !important; -webkit-animation-name: flipInX; animation-name: flipInX; } @-webkit-keyframes flipInY { 0% { -webkit-transform: perspective(400px) rotateY(90deg); transform: perspective(400px) rotateY(90deg); opacity: 0; } 40% { -webkit-transform: perspective(400px) rotateY(-10deg); transform: perspective(400px) rotateY(-10deg); } 70% { -webkit-transform: perspective(400px) rotateY(10deg); transform: perspective(400px) rotateY(10deg); } 100% { -webkit-transform: perspective(400px) rotateY(0deg); transform: perspective(400px) rotateY(0deg); opacity: 1; } } @keyframes flipInY { 0% { -webkit-transform: perspective(400px) rotateY(90deg); -ms-transform: perspective(400px) rotateY(90deg); transform: perspective(400px) rotateY(90deg); opacity: 0; } 40% { -webkit-transform: perspective(400px) rotateY(-10deg); -ms-transform: perspective(400px) rotateY(-10deg); transform: perspective(400px) rotateY(-10deg); } 70% { -webkit-transform: perspective(400px) rotateY(10deg); -ms-transform: perspective(400px) rotateY(10deg); transform: perspective(400px) rotateY(10deg); } 100% { -webkit-transform: perspective(400px) rotateY(0deg); -ms-transform: perspective(400px) rotateY(0deg); transform: perspective(400px) rotateY(0deg); opacity: 1; } } .flipInY { -webkit-backface-visibility: visible !important; -ms-backface-visibility: visible !important; backface-visibility: visible !important; -webkit-animation-name: flipInY; animation-name: flipInY; } @-webkit-keyframes flipOutX { 0% { -webkit-transform: perspective(400px) rotateX(0deg); transform: perspective(400px) rotateX(0deg); opacity: 1; } 100% { -webkit-transform: perspective(400px) rotateX(90deg); transform: perspective(400px) rotateX(90deg); opacity: 0; } } @keyframes flipOutX { 0% { -webkit-transform: perspective(400px) rotateX(0deg); -ms-transform: perspective(400px) rotateX(0deg); transform: perspective(400px) rotateX(0deg); opacity: 1; } 100% { -webkit-transform: perspective(400px) rotateX(90deg); -ms-transform: perspective(400px) rotateX(90deg); transform: perspective(400px) rotateX(90deg); opacity: 0; } } .flipOutX { -webkit-animation-name: flipOutX; animation-name: flipOutX; -webkit-backface-visibility: visible !important; -ms-backface-visibility: visible !important; backface-visibility: visible !important; } @-webkit-keyframes flipOutY { 0% { -webkit-transform: perspective(400px) rotateY(0deg); transform: perspective(400px) rotateY(0deg); opacity: 1; } 100% { -webkit-transform: perspective(400px) rotateY(90deg); transform: perspective(400px) rotateY(90deg); opacity: 0; } } @keyframes flipOutY { 0% { -webkit-transform: perspective(400px) rotateY(0deg); -ms-transform: perspective(400px) rotateY(0deg); transform: perspective(400px) rotateY(0deg); opacity: 1; } 100% { -webkit-transform: perspective(400px) rotateY(90deg); -ms-transform: perspective(400px) rotateY(90deg); transform: perspective(400px) rotateY(90deg); opacity: 0; } } .flipOutY { -webkit-backface-visibility: visible !important; -ms-backface-visibility: visible !important; backface-visibility: visible !important; -webkit-animation-name: flipOutY; animation-name: flipOutY; } @-webkit-keyframes lightSpeedIn { 0% { -webkit-transform: translateX(100%) skewX(-30deg); transform: translateX(100%) skewX(-30deg); opacity: 0; } 60% { -webkit-transform: translateX(-20%) skewX(30deg); transform: translateX(-20%) skewX(30deg); opacity: 1; } 80% { -webkit-transform: translateX(0%) skewX(-15deg); transform: translateX(0%) skewX(-15deg); opacity: 1; } 100% { -webkit-transform: translateX(0%) skewX(0deg); transform: translateX(0%) skewX(0deg); opacity: 1; } } @keyframes lightSpeedIn { 0% { -webkit-transform: translateX(100%) skewX(-30deg); -ms-transform: translateX(100%) skewX(-30deg); transform: translateX(100%) skewX(-30deg); opacity: 0; } 60% { -webkit-transform: translateX(-20%) skewX(30deg); -ms-transform: translateX(-20%) skewX(30deg); transform: translateX(-20%) skewX(30deg); opacity: 1; } 80% { -webkit-transform: translateX(0%) skewX(-15deg); -ms-transform: translateX(0%) skewX(-15deg); transform: translateX(0%) skewX(-15deg); opacity: 1; } 100% { -webkit-transform: translateX(0%) skewX(0deg); -ms-transform: translateX(0%) skewX(0deg); transform: translateX(0%) skewX(0deg); opacity: 1; } } .lightSpeedIn { -webkit-animation-name: lightSpeedIn; animation-name: lightSpeedIn; -webkit-animation-timing-function: ease-out; animation-timing-function: ease-out; } @-webkit-keyframes lightSpeedOut { 0% { -webkit-transform: translateX(0%) skewX(0deg); transform: translateX(0%) skewX(0deg); opacity: 1; } 100% { -webkit-transform: translateX(100%) skewX(-30deg); transform: translateX(100%) skewX(-30deg); opacity: 0; } } @keyframes lightSpeedOut { 0% { -webkit-transform: translateX(0%) skewX(0deg); -ms-transform: translateX(0%) skewX(0deg); transform: translateX(0%) skewX(0deg); opacity: 1; } 100% { -webkit-transform: translateX(100%) skewX(-30deg); -ms-transform: translateX(100%) skewX(-30deg); transform: translateX(100%) skewX(-30deg); opacity: 0; } } .lightSpeedOut { -webkit-animation-name: lightSpeedOut; animation-name: lightSpeedOut; -webkit-animation-timing-function: ease-in; animation-timing-function: ease-in; } @-webkit-keyframes rotateIn { 0% { -webkit-transform-origin: center center; transform-origin: center center; -webkit-transform: rotate(-200deg); transform: rotate(-200deg); opacity: 0; } 100% { -webkit-transform-origin: center center; transform-origin: center center; -webkit-transform: rotate(0); transform: rotate(0); opacity: 1; } } @keyframes rotateIn { 0% { -webkit-transform-origin: center center; -ms-transform-origin: center center; transform-origin: center center; -webkit-transform: rotate(-200deg); -ms-transform: rotate(-200deg); transform: rotate(-200deg); opacity: 0; } 100% { -webkit-transform-origin: center center; -ms-transform-origin: center center; transform-origin: center center; -webkit-transform: rotate(0); -ms-transform: rotate(0); transform: rotate(0); opacity: 1; } } .rotateIn { -webkit-animation-name: rotateIn; animation-name: rotateIn; } @-webkit-keyframes rotateInDownLeft { 0% { -webkit-transform-origin: left bottom; transform-origin: left bottom; -webkit-transform: rotate(-90deg); transform: rotate(-90deg); opacity: 0; } 100% { -webkit-transform-origin: left bottom; transform-origin: left bottom; -webkit-transform: rotate(0); transform: rotate(0); opacity: 1; } } @keyframes rotateInDownLeft { 0% { -webkit-transform-origin: left bottom; -ms-transform-origin: left bottom; transform-origin: left bottom; -webkit-transform: rotate(-90deg); -ms-transform: rotate(-90deg); transform: rotate(-90deg); opacity: 0; } 100% { -webkit-transform-origin: left bottom; -ms-transform-origin: left bottom; transform-origin: left bottom; -webkit-transform: rotate(0); -ms-transform: rotate(0); transform: rotate(0); opacity: 1; } } .rotateInDownLeft { -webkit-animation-name: rotateInDownLeft; animation-name: rotateInDownLeft; } @-webkit-keyframes rotateInDownRight { 0% { -webkit-transform-origin: right bottom; transform-origin: right bottom; -webkit-transform: rotate(90deg); transform: rotate(90deg); opacity: 0; } 100% { -webkit-transform-origin: right bottom; transform-origin: right bottom; -webkit-transform: rotate(0); transform: rotate(0); opacity: 1; } } @keyframes rotateInDownRight { 0% { -webkit-transform-origin: right bottom; -ms-transform-origin: right bottom; transform-origin: right bottom; -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); opacity: 0; } 100% { -webkit-transform-origin: right bottom; -ms-transform-origin: right bottom; transform-origin: right bottom; -webkit-transform: rotate(0); -ms-transform: rotate(0); transform: rotate(0); opacity: 1; } } .rotateInDownRight { -webkit-animation-name: rotateInDownRight; animation-name: rotateInDownRight; } @-webkit-keyframes rotateInUpLeft { 0% { -webkit-transform-origin: left bottom; transform-origin: left bottom; -webkit-transform: rotate(90deg); transform: rotate(90deg); opacity: 0; } 100% { -webkit-transform-origin: left bottom; transform-origin: left bottom; -webkit-transform: rotate(0); transform: rotate(0); opacity: 1; } } @keyframes rotateInUpLeft { 0% { -webkit-transform-origin: left bottom; -ms-transform-origin: left bottom; transform-origin: left bottom; -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); opacity: 0; } 100% { -webkit-transform-origin: left bottom; -ms-transform-origin: left bottom; transform-origin: left bottom; -webkit-transform: rotate(0); -ms-transform: rotate(0); transform: rotate(0); opacity: 1; } } .rotateInUpLeft { -webkit-animation-name: rotateInUpLeft; animation-name: rotateInUpLeft; } @-webkit-keyframes rotateInUpRight { 0% { -webkit-transform-origin: right bottom; transform-origin: right bottom; -webkit-transform: rotate(-90deg); transform: rotate(-90deg); opacity: 0; } 100% { -webkit-transform-origin: right bottom; transform-origin: right bottom; -webkit-transform: rotate(0); transform: rotate(0); opacity: 1; } } @keyframes rotateInUpRight { 0% { -webkit-transform-origin: right bottom; -ms-transform-origin: right bottom; transform-origin: right bottom; -webkit-transform: rotate(-90deg); -ms-transform: rotate(-90deg); transform: rotate(-90deg); opacity: 0; } 100% { -webkit-transform-origin: right bottom; -ms-transform-origin: right bottom; transform-origin: right bottom; -webkit-transform: rotate(0); -ms-transform: rotate(0); transform: rotate(0); opacity: 1; } } .rotateInUpRight { -webkit-animation-name: rotateInUpRight; animation-name: rotateInUpRight; } @-webkit-keyframes rotateOut { 0% { -webkit-transform-origin: center center; transform-origin: center center; -webkit-transform: rotate(0); transform: rotate(0); opacity: 1; } 100% { -webkit-transform-origin: center center; transform-origin: center center; -webkit-transform: rotate(200deg); transform: rotate(200deg); opacity: 0; } } @keyframes rotateOut { 0% { -webkit-transform-origin: center center; -ms-transform-origin: center center; transform-origin: center center; -webkit-transform: rotate(0); -ms-transform: rotate(0); transform: rotate(0); opacity: 1; } 100% { -webkit-transform-origin: center center; -ms-transform-origin: center center; transform-origin: center center; -webkit-transform: rotate(200deg); -ms-transform: rotate(200deg); transform: rotate(200deg); opacity: 0; } } .rotateOut { -webkit-animation-name: rotateOut; animation-name: rotateOut; } @-webkit-keyframes rotateOutDownLeft { 0% { -webkit-transform-origin: left bottom; transform-origin: left bottom; -webkit-transform: rotate(0); transform: rotate(0); opacity: 1; } 100% { -webkit-transform-origin: left bottom; transform-origin: left bottom; -webkit-transform: rotate(90deg); transform: rotate(90deg); opacity: 0; } } @keyframes rotateOutDownLeft { 0% { -webkit-transform-origin: left bottom; -ms-transform-origin: left bottom; transform-origin: left bottom; -webkit-transform: rotate(0); -ms-transform: rotate(0); transform: rotate(0); opacity: 1; } 100% { -webkit-transform-origin: left bottom; -ms-transform-origin: left bottom; transform-origin: left bottom; -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); opacity: 0; } } .rotateOutDownLeft { -webkit-animation-name: rotateOutDownLeft; animation-name: rotateOutDownLeft; } @-webkit-keyframes rotateOutDownRight { 0% { -webkit-transform-origin: right bottom; transform-origin: right bottom; -webkit-transform: rotate(0); transform: rotate(0); opacity: 1; } 100% { -webkit-transform-origin: right bottom; transform-origin: right bottom; -webkit-transform: rotate(-90deg); transform: rotate(-90deg); opacity: 0; } } @keyframes rotateOutDownRight { 0% { -webkit-transform-origin: right bottom; -ms-transform-origin: right bottom; transform-origin: right bottom; -webkit-transform: rotate(0); -ms-transform: rotate(0); transform: rotate(0); opacity: 1; } 100% { -webkit-transform-origin: right bottom; -ms-transform-origin: right bottom; transform-origin: right bottom; -webkit-transform: rotate(-90deg); -ms-transform: rotate(-90deg); transform: rotate(-90deg); opacity: 0; } } .rotateOutDownRight { -webkit-animation-name: rotateOutDownRight; animation-name: rotateOutDownRight; } @-webkit-keyframes rotateOutUpLeft { 0% { -webkit-transform-origin: left bottom; transform-origin: left bottom; -webkit-transform: rotate(0); transform: rotate(0); opacity: 1; } 100% { -webkit-transform-origin: left bottom; transform-origin: left bottom; -webkit-transform: rotate(-90deg); transform: rotate(-90deg); opacity: 0; } } @keyframes rotateOutUpLeft { 0% { -webkit-transform-origin: left bottom; -ms-transform-origin: left bottom; transform-origin: left bottom; -webkit-transform: rotate(0); -ms-transform: rotate(0); transform: rotate(0); opacity: 1; } 100% { -webkit-transform-origin: left bottom; -ms-transform-origin: left bottom; transform-origin: left bottom; -webkit-transform: rotate(-90deg); -ms-transform: rotate(-90deg); transform: rotate(-90deg); opacity: 0; } } .rotateOutUpLeft { -webkit-animation-name: rotateOutUpLeft; animation-name: rotateOutUpLeft; } @-webkit-keyframes rotateOutUpRight { 0% { -webkit-transform-origin: right bottom; transform-origin: right bottom; -webkit-transform: rotate(0); transform: rotate(0); opacity: 1; } 100% { -webkit-transform-origin: right bottom; transform-origin: right bottom; -webkit-transform: rotate(90deg); transform: rotate(90deg); opacity: 0; } } @keyframes rotateOutUpRight { 0% { -webkit-transform-origin: right bottom; -ms-transform-origin: right bottom; transform-origin: right bottom; -webkit-transform: rotate(0); -ms-transform: rotate(0); transform: rotate(0); opacity: 1; } 100% { -webkit-transform-origin: right bottom; -ms-transform-origin: right bottom; transform-origin: right bottom; -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); opacity: 0; } } .rotateOutUpRight { -webkit-animation-name: rotateOutUpRight; animation-name: rotateOutUpRight; } @-webkit-keyframes slideInDown { 0% { opacity: 0; -webkit-transform: translateY(-2000px); transform: translateY(-2000px); } 100% { -webkit-transform: translateY(0); transform: translateY(0); } } @keyframes slideInDown { 0% { opacity: 0; -webkit-transform: translateY(-2000px); -ms-transform: translateY(-2000px); transform: translateY(-2000px); } 100% { -webkit-transform: translateY(0); -ms-transform: translateY(0); transform: translateY(0); } } .slideInDown { -webkit-animation-name: slideInDown; animation-name: slideInDown; } @-webkit-keyframes slideInLeft { 0% { opacity: 0; -webkit-transform: translateX(-2000px); transform: translateX(-2000px); } 100% { -webkit-transform: translateX(0); transform: translateX(0); } } @keyframes slideInLeft { 0% { opacity: 0; -webkit-transform: translateX(-2000px); -ms-transform: translateX(-2000px); transform: translateX(-2000px); } 100% { -webkit-transform: translateX(0); -ms-transform: translateX(0); transform: translateX(0); } } .slideInLeft { -webkit-animation-name: slideInLeft; animation-name: slideInLeft; } @-webkit-keyframes slideInRight { 0% { opacity: 0; -webkit-transform: translateX(2000px); transform: translateX(2000px); } 100% { -webkit-transform: translateX(0); transform: translateX(0); } } @keyframes slideInRight { 0% { opacity: 0; -webkit-transform: translateX(2000px); -ms-transform: translateX(2000px); transform: translateX(2000px); } 100% { -webkit-transform: translateX(0); -ms-transform: translateX(0); transform: translateX(0); } } .slideInRight { -webkit-animation-name: slideInRight; animation-name: slideInRight; } @-webkit-keyframes slideOutLeft { 0% { -webkit-transform: translateX(0); transform: translateX(0); } 100% { opacity: 0; -webkit-transform: translateX(-2000px); transform: translateX(-2000px); } } @keyframes slideOutLeft { 0% { -webkit-transform: translateX(0); -ms-transform: translateX(0); transform: translateX(0); } 100% { opacity: 0; -webkit-transform: translateX(-2000px); -ms-transform: translateX(-2000px); transform: translateX(-2000px); } } .slideOutLeft { -webkit-animation-name: slideOutLeft; animation-name: slideOutLeft; } @-webkit-keyframes slideOutRight { 0% { -webkit-transform: translateX(0); transform: translateX(0); } 100% { opacity: 0; -webkit-transform: translateX(2000px); transform: translateX(2000px); } } @keyframes slideOutRight { 0% { -webkit-transform: translateX(0); -ms-transform: translateX(0); transform: translateX(0); } 100% { opacity: 0; -webkit-transform: translateX(2000px); -ms-transform: translateX(2000px); transform: translateX(2000px); } } .slideOutRight { -webkit-animation-name: slideOutRight; animation-name: slideOutRight; } @-webkit-keyframes slideOutUp { 0% { -webkit-transform: translateY(0); transform: translateY(0); } 100% { opacity: 0; -webkit-transform: translateY(-2000px); transform: translateY(-2000px); } } @keyframes slideOutUp { 0% { -webkit-transform: translateY(0); -ms-transform: translateY(0); transform: translateY(0); } 100% { opacity: 0; -webkit-transform: translateY(-2000px); -ms-transform: translateY(-2000px); transform: translateY(-2000px); } } .slideOutUp { -webkit-animation-name: slideOutUp; animation-name: slideOutUp; } @-webkit-keyframes hinge { 0% { -webkit-transform: rotate(0); transform: rotate(0); -webkit-transform-origin: top left; transform-origin: top left; -webkit-animation-timing-function: ease-in-out; animation-timing-function: ease-in-out; } 20%, 60% { -webkit-transform: rotate(80deg); transform: rotate(80deg); -webkit-transform-origin: top left; transform-origin: top left; -webkit-animation-timing-function: ease-in-out; animation-timing-function: ease-in-out; } 40% { -webkit-transform: rotate(60deg); transform: rotate(60deg); -webkit-transform-origin: top left; transform-origin: top left; -webkit-animation-timing-function: ease-in-out; animation-timing-function: ease-in-out; } 80% { -webkit-transform: rotate(60deg) translateY(0); transform: rotate(60deg) translateY(0); opacity: 1; -webkit-transform-origin: top left; transform-origin: top left; -webkit-animation-timing-function: ease-in-out; animation-timing-function: ease-in-out; } 100% { -webkit-transform: translateY(700px); transform: translateY(700px); opacity: 0; } } @keyframes hinge { 0% { -webkit-transform: rotate(0); -ms-transform: rotate(0); transform: rotate(0); -webkit-transform-origin: top left; -ms-transform-origin: top left; transform-origin: top left; -webkit-animation-timing-function: ease-in-out; animation-timing-function: ease-in-out; } 20%, 60% { -webkit-transform: rotate(80deg); -ms-transform: rotate(80deg); transform: rotate(80deg); -webkit-transform-origin: top left; -ms-transform-origin: top left; transform-origin: top left; -webkit-animation-timing-function: ease-in-out; animation-timing-function: ease-in-out; } 40% { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); -webkit-transform-origin: top left; -ms-transform-origin: top left; transform-origin: top left; -webkit-animation-timing-function: ease-in-out; animation-timing-function: ease-in-out; } 80% { -webkit-transform: rotate(60deg) translateY(0); -ms-transform: rotate(60deg) translateY(0); transform: rotate(60deg) translateY(0); opacity: 1; -webkit-transform-origin: top left; -ms-transform-origin: top left; transform-origin: top left; -webkit-animation-timing-function: ease-in-out; animation-timing-function: ease-in-out; } 100% { -webkit-transform: translateY(700px); -ms-transform: translateY(700px); transform: translateY(700px); opacity: 0; } } .hinge { -webkit-animation-name: hinge; animation-name: hinge; } /* originally authored by Nick Pettit - https://github.com/nickpettit/glide */ @-webkit-keyframes rollIn { 0% { opacity: 0; -webkit-transform: translateX(-100%) rotate(-120deg); transform: translateX(-100%) rotate(-120deg); } 100% { opacity: 1; -webkit-transform: translateX(0px) rotate(0deg); transform: translateX(0px) rotate(0deg); } } @keyframes rollIn { 0% { opacity: 0; -webkit-transform: translateX(-100%) rotate(-120deg); -ms-transform: translateX(-100%) rotate(-120deg); transform: translateX(-100%) rotate(-120deg); } 100% { opacity: 1; -webkit-transform: translateX(0px) rotate(0deg); -ms-transform: translateX(0px) rotate(0deg); transform: translateX(0px) rotate(0deg); } } .rollIn { -webkit-animation-name: rollIn; animation-name: rollIn; } /* originally authored by Nick Pettit - https://github.com/nickpettit/glide */ @-webkit-keyframes rollOut { 0% { opacity: 1; -webkit-transform: translateX(0px) rotate(0deg); transform: translateX(0px) rotate(0deg); } 100% { opacity: 0; -webkit-transform: translateX(100%) rotate(120deg); transform: translateX(100%) rotate(120deg); } } @keyframes rollOut { 0% { opacity: 1; -webkit-transform: translateX(0px) rotate(0deg); -ms-transform: translateX(0px) rotate(0deg); transform: translateX(0px) rotate(0deg); } 100% { opacity: 0; -webkit-transform: translateX(100%) rotate(120deg); -ms-transform: translateX(100%) rotate(120deg); transform: translateX(100%) rotate(120deg); } } .rollOut { -webkit-animation-name: rollOut; animation-name: rollOut; } .looper { position: relative; z-index: 1; line-height: 1; width: auto; height: auto; } .looper:focus { outline: 0; } .looper .looper-inner { overflow: hidden; width: 100%; height: auto; position: relative; z-index: 2; } .looper .item { display: none; position: relative; z-index: 3; } .looper .item.active, .looper .item.next, .looper .item.prev { display: block; } .looper .item.active { top: 0; left: 0; z-index: 4; } .looper .item > img { display: block; line-height: 1; } .looper.xfade .looper-inner { height: 100%; } .looper.xfade .item { -webkit-transition: 0.5s ease-in opacity; -moz-transition: 0.5s ease-in opacity; -o-transition: 0.5s ease-in opacity; transition: 0.5s ease-in opacity; position: absolute; width: 100%; opacity: 0; } .looper.xfade .item.go { opacity: 1; } .looper.xfade .item.active { opacity: 1; } .looper.xfade .item.active.go { opacity: 0; } .looper.slide.xfade .item { -webkit-transition: 0.5s ease-in-out left, 0.5s ease-in opacity; -moz-transition: 0.5s ease-in-out left, 0.5s ease-in opacity; -o-transition: 0.5s ease-in-out left, 0.5s ease-in opacity; transition: 0.5s ease-in-out left, 0.5s ease-in opacity; } .looper.slide .item { -webkit-transition: 0.5s ease-in-out left; -moz-transition: 0.5s ease-in-out left; -o-transition: 0.5s ease-in-out left; transition: 0.5s ease-in-out left; } .looper.slide .item.next, .looper.slide .item.prev { position: absolute; top: 0; left: 0; width: 100%; } .looper.slide .item.next { left: 100%; } .looper.slide .item.prev { left: -100%; } .looper.slide .item.active.prev, .looper.slide .item.active.next { position: relative; left: 0; } .looper.slide .item.go { left: 0; } .looper.slide .item.go.active { left: -100%; } .looper.slide .item.go.active.prev { left: 100%; } .looper.slide.right .item.next { left: -100%; } .looper.slide.right .item.prev { left: 100%; } .looper.slide.right .item.go { left: 0; } .looper.slide.right .item.go.active { left: 100%; } .looper.slide.right .item.go.active.prev { left: -100%; } .looper.slide.down .looper-inner { height: 100%; } .looper.slide.down .item { -webkit-transition: 0.5s ease-in-out top; -moz-transition: 0.5s ease-in-out top; -o-transition: 0.5s ease-in-out top; transition: 0.5s ease-in-out top; } .looper.slide.down .item.next, .looper.slide.down .item.prev { left: 0; } .looper.slide.down .item.next { top: -100%; } .looper.slide.down .item.prev { top: 100%; } .looper.slide.down .item.go { top: 0; } .looper.slide.down .item.go.active { top: 100%; left: 0; } .looper.slide.down .item.go.active.prev { top: -100%; } .looper.slide.down.xfade .item { -webkit-transition: 0.5s ease-in-out top, 0.5s ease-in opacity; -moz-transition: 0.5s ease-in-out top, 0.5s ease-in opacity; -o-transition: 0.5s ease-in-out top, 0.5s ease-in opacity; transition: 0.5s ease-in-out top, 0.5s ease-in opacity; } .looper.slide.up .looper-inner { height: 100%; } .looper.slide.up .item { -webkit-transition: 0.5s ease-in-out top; -moz-transition: 0.5s ease-in-out top; -o-transition: 0.5s ease-in-out top; transition: 0.5s ease-in-out top; } .looper.slide.up .item.next, .looper.slide.up .item.prev { left: 0; } .looper.slide.up .item.next { top: 100%; } .looper.slide.up .item.prev { top: -100%; } .looper.slide.up .item.go { top: 0; } .looper.slide.up .item.go.active { top: -100%; left: 0; } .looper.slide.up .item.go.active.prev { top: 100%; } .looper.slide.up.xfade .item { -webkit-transition: 0.5s ease-in-out top, 0.5s ease-in opacity; -moz-transition: 0.5s ease-in-out top, 0.5s ease-in opacity; -o-transition: 0.5s ease-in-out top, 0.5s ease-in opacity; transition: 0.5s ease-in-out top, 0.5s ease-in opacity; } .looper-control { position: absolute; z-index: 5; top: 50%; left: -20px; width: 40px; height: 40px; margin-top: -20px; font-size: 30px; line-height: 40px; color: #ffffff; text-align: center; cursor: pointer; background: #333333; border: 3px solid #ffffff; -webkit-border-radius: 23px; -moz-border-radius: 23px; border-radius: 23px; opacity: 0.5; filter: alpha(opacity=50); -webkit-transition: none; -moz-transition: none; -o-transition: none; transition: none; } .looper-control.right { left: auto; right: -20px; } .looper-control:hover { color: #ffffff; text-decoration: none; text-shadow: none; opacity: 0.9; filter: alpha(opacity=90); } .looper-nav { background: transparent; text-align: center; list-style-type: none; margin: 0; } .looper-nav > li { display: inline-block; font-size: 36px; } .looper-nav > li a { color: #049cdb; } .looper-nav > li a:hover { color: #036690; } .looper-nav > li.active a, .looper-nav > li.active a:hover { color: #036690; } body { display: none; } #jpreOverlay { background-color: #000000; } #jpreSlide { font-size: 22px; font-weight: bold; color: #ccc; text-align: center; width: 50%; height: 30%; } #jpreLoader { width: 300px; height: 25px; box-shadow: 0 0 7px 3px #fff; -moz-box-shadow: 0 0 7px 3px #fff; -webkit-box-shadow: 0 0 7px 3px #fff; border-radius: 25px; -moz-border-radius: 25px; -webkit-border-radius: 25px; } #jpreBar { border-radius: 25px; -moz-border-radius: 25px; -webkit-border-radius: 25px; background-size: 30px 30px; -moz-background-size: 30px 30px; -webkit-background-size: 30px 30px; -o-background-size: 30px 30px; box-shadow: 0 5px 5px rgba(255, 255, 255, 0.6) inset, 0 -5px 7px rgba(0, 0, 0, 0.4) inset; -moz-box-shadow: 0 5px 5px rgba(255, 255, 255, 0.6) inset, 0 -5px 7px rgba(0, 0, 0, 0.4) inset; -webkit-box-shadow: 0 5px 5px rgba(255, 255, 255, 0.6) inset, 0 -5px 7px rgba(0, 0, 0, 0.4) inset; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#33ffffff', endColorstr='#33000000', GradientType=0 ); background-color: #E07300; background-image: -moz-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0.15) 25%, rgba(255, 255, 255, 0) 25%, rgba(255, 255, 255, 0) 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, rgba(255, 255, 255, 0) 75%, rgba(255, 255, 255, 0) 100%); background-image: -webkit-gradient(linear, left top, right bottom, color-stop(0%, rgba(255, 255, 255, 0.2)), color-stop(25%, rgba(255, 255, 255, 0.2)), color-stop(25%, rgba(255, 255, 255, 0)), color-stop(50%, rgba(255, 255, 255, 0)), color-stop(50%, rgba(255, 255, 255, 0.2)), color-stop(75%, rgba(255, 255, 255, 0.2)), color-stop(75%, rgba(255, 255, 255, 0)), color-stop(100%, rgba(255, 255, 255, 0))); background-image: -webkit-linear-gradient(-45deg, rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0.3) 25%, rgba(255, 255, 255, 0) 25%, rgba(255, 255, 255, 0) 50%, rgba(255, 255, 255, 0.3) 50%, rgba(255, 255, 255, 0.3) 75%, rgba(255, 255, 255, 0) 75%, rgba(255, 255, 255, 0) 100%); background-image: -o-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0.15) 25%, rgba(255, 255, 255, 0) 25%, rgba(255, 255, 255, 0) 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, rgba(255, 255, 255, 0) 75%, rgba(255, 255, 255, 0) 100%); background-image: -ms-linear-gradient(-45deg, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0.15) 25%, rgba(255, 255, 255, 0) 25%, rgba(255, 255, 255, 0) 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, rgba(255, 255, 255, 0) 75%, rgba(255, 255, 255, 0) 100%); background-image: linear-gradient(135deg, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0.15) 25%, rgba(255, 255, 255, 0) 25%, rgba(255, 255, 255, 0) 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, rgba(255, 255, 255, 0) 75%, rgba(255, 255, 255, 0) 100%); animation: progress 2s linear infinite; -moz-animation: progress 2s linear infinite; -webkit-animation: progress 2s linear infinite; -ms-animation: progress 2s linear infinite; -o-animation: progress 2s linear infinite; } #jprePercentage { color: #ccc; font-family: "Trebuchet MS",Arial,Helvetica,sans-serif; font-weight: bold; text-align: center; text-shadow: 1px 1px 1px #333; top: -100%; } #jpreButton { padding: 3px 10px; cursor: pointer; font-weight: bold; line-height: 1.5; text-align: center; width: 100px; margin: 0 auto; color: #fff; text-shadow: -1px -1px 0 #01293F; border: 1px solid #2EACEA; border-radius: 30px; -moz-border-radius: 30px; -webkit-border-radius: 30px; background-color: #23a6ed; background-image: -moz-linear-gradient(top, #23a6ed 0%, #1275aa 100%); background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #23a6ed), color-stop(100%, #1275aa)); background-image: -webkit-linear-gradient(top, #23a6ed 0%, #1275aa 100%); background-image: -o-linear-gradient(top, #23a6ed 0%, #1275aa 100%); background-image: -ms-linear-gradient(top, #23a6ed 0%, #1275aa 100%); background-image: linear-gradient(to bottom, #23a6ed 0%, #1275aa 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#23a6ed', endColorstr='#1275aa',GradientType=0 ); } @-webkit-keyframes progress { from { background-position: 0 0; } to { background-position: -60px -60px; } } @-moz-keyframes progress { from { background-position: 0 0; } to { background-position: -60px -60px; } } @-ms-keyframes progress { from { background-position: 0 0; } to { background-position: -60px -60px; } } @-o-keyframes progress { from { background-position: 0 0; } to { background-position: -60px -60px; } } @keyframes progress { from { background-position: 0 0; } to { background-position: -60px -60px; } } /* Magnific Popup CSS */ .mfp-bg { top: 0; left: 0; width: 100%; height: 100%; z-index: 1042; overflow: hidden; position: fixed; background: #0b0b0b; opacity: 0.8; filter: alpha(opacity=80); } .mfp-wrap { top: 0; left: 0; width: 100%; height: 100%; z-index: 1043; position: fixed; outline: none !important; -webkit-backface-visibility: hidden; } .mfp-container { text-align: center; position: absolute; width: 100%; height: 100%; left: 0; top: 0; padding: 0 8px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .mfp-container:before { content: ''; display: inline-block; height: 100%; vertical-align: middle; } .mfp-align-top .mfp-container:before { display: none; } .mfp-content { position: relative; display: inline-block; vertical-align: middle; margin: 0 auto; text-align: left; z-index: 1045; } .mfp-inline-holder .mfp-content, .mfp-ajax-holder .mfp-content { width: 100%; cursor: auto; } .mfp-ajax-cur { cursor: progress; } .mfp-zoom-out-cur, .mfp-zoom-out-cur .mfp-image-holder .mfp-close { cursor: -moz-zoom-out; cursor: -webkit-zoom-out; cursor: zoom-out; } .mfp-zoom { cursor: pointer; cursor: -webkit-zoom-in; cursor: -moz-zoom-in; cursor: zoom-in; } .mfp-auto-cursor .mfp-content { cursor: auto; } .mfp-close, .mfp-arrow, .mfp-preloader, .mfp-counter { -webkit-user-select: none; -moz-user-select: none; user-select: none; } .mfp-loading.mfp-figure { display: none; } .mfp-hide { display: none !important; } .mfp-preloader { color: #cccccc; position: absolute; top: 50%; width: auto; text-align: center; margin-top: -0.8em; left: 8px; right: 8px; z-index: 1044; } .mfp-preloader a { color: #cccccc; } .mfp-preloader a:hover { color: white; } .mfp-s-ready .mfp-preloader { display: none; } .mfp-s-error .mfp-content { display: none; } button.mfp-close, button.mfp-arrow { overflow: visible; cursor: pointer; background: transparent; border: 0; -webkit-appearance: none; display: block; outline: none; padding: 0; z-index: 1046; -webkit-box-shadow: none; box-shadow: none; } button::-moz-focus-inner { padding: 0; border: 0; } .mfp-close { width: 44px; height: 44px; line-height: 44px; position: absolute; right: 0; top: 0; text-decoration: none; text-align: center; opacity: 0.65; filter: alpha(opacity=65); padding: 0 0 18px 10px; color: white; font-style: normal; font-size: 28px; font-family: Arial, Baskerville, monospace; } .mfp-close:hover, .mfp-close:focus { opacity: 1; filter: alpha(opacity=100); } .mfp-close:active { top: 1px; } .mfp-close-btn-in .mfp-close { color: #333333; } .mfp-image-holder .mfp-close, .mfp-iframe-holder .mfp-close { color: white; right: -6px; text-align: right; padding-right: 6px; width: 100%; } .mfp-counter { position: absolute; top: 0; right: 0; color: #cccccc; font-size: 12px; line-height: 18px; } .mfp-arrow { position: absolute; opacity: 0.65; filter: alpha(opacity=65); margin: 0; top: 50%; margin-top: -55px; padding: 0; width: 90px; height: 110px; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); } .mfp-arrow:active { margin-top: -54px; } .mfp-arrow:hover, .mfp-arrow:focus { opacity: 1; filter: alpha(opacity=100); } .mfp-arrow:before, .mfp-arrow:after, .mfp-arrow .mfp-b, .mfp-arrow .mfp-a { content: ''; display: block; width: 0; height: 0; position: absolute; left: 0; top: 0; margin-top: 35px; margin-left: 35px; border: medium inset transparent; } .mfp-arrow:after, .mfp-arrow .mfp-a { border-top-width: 13px; border-bottom-width: 13px; top: 8px; } .mfp-arrow:before, .mfp-arrow .mfp-b { border-top-width: 21px; border-bottom-width: 21px; opacity: 0.7; } .mfp-arrow-left { left: 0; } .mfp-arrow-left:after, .mfp-arrow-left .mfp-a { border-right: 17px solid white; margin-left: 31px; } .mfp-arrow-left:before, .mfp-arrow-left .mfp-b { margin-left: 25px; border-right: 27px solid #3f3f3f; } .mfp-arrow-right { right: 0; } .mfp-arrow-right:after, .mfp-arrow-right .mfp-a { border-left: 17px solid white; margin-left: 39px; } .mfp-arrow-right:before, .mfp-arrow-right .mfp-b { border-left: 27px solid #3f3f3f; } .mfp-iframe-holder { padding-top: 40px; padding-bottom: 40px; } .mfp-iframe-holder .mfp-content { line-height: 0; width: 100%; max-width: 900px; } .mfp-iframe-holder .mfp-close { top: -40px; } .mfp-iframe-scaler { width: 100%; height: 0; overflow: hidden; padding-top: 56.25%; } .mfp-iframe-scaler iframe { position: absolute; display: block; top: 0; left: 0; width: 100%; height: 100%; box-shadow: 0 0 8px rgba(0, 0, 0, 0.6); background: black; } /* Main image in popup */ img.mfp-img { width: auto; max-width: 100%; height: auto; display: block; line-height: 0; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; padding: 40px 0 40px; margin: 0 auto; } /* The shadow behind the image */ .mfp-figure { line-height: 0; } .mfp-figure:after { content: ''; position: absolute; left: 0; top: 40px; bottom: 40px; display: block; right: 0; width: auto; height: auto; z-index: -1; box-shadow: 0 0 8px rgba(0, 0, 0, 0.6); background: #444444; } .mfp-figure small { color: #bdbdbd; display: block; font-size: 12px; line-height: 14px; } .mfp-figure figure { margin: 0; } .mfp-bottom-bar { margin-top: -36px; position: absolute; top: 100%; left: 0; width: 100%; cursor: auto; } .mfp-title { text-align: left; line-height: 18px; color: #f3f3f3; word-wrap: break-word; padding-right: 36px; } .mfp-image-holder .mfp-content { max-width: 100%; } .mfp-gallery .mfp-image-holder .mfp-figure { cursor: pointer; } @media screen and (max-width: 800px) and (orientation: landscape), screen and (max-height: 300px) { /** * Remove all paddings around the image on small screen */ .mfp-img-mobile .mfp-image-holder { padding-left: 0; padding-right: 0; } .mfp-img-mobile img.mfp-img { padding: 0; } .mfp-img-mobile .mfp-figure:after { top: 0; bottom: 0; } .mfp-img-mobile .mfp-figure small { display: inline; margin-left: 5px; } .mfp-img-mobile .mfp-bottom-bar { background: rgba(0, 0, 0, 0.6); bottom: 0; margin: 0; top: auto; padding: 3px 5px; position: fixed; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .mfp-img-mobile .mfp-bottom-bar:empty { padding: 0; } .mfp-img-mobile .mfp-counter { right: 5px; top: 3px; } .mfp-img-mobile .mfp-close { top: 0; right: 0; width: 35px; height: 35px; line-height: 35px; background: rgba(0, 0, 0, 0.6); position: fixed; text-align: center; padding: 0; } } @media all and (max-width: 900px) { .mfp-arrow { -webkit-transform: scale(0.75); transform: scale(0.75); } .mfp-arrow-left { -webkit-transform-origin: 0; transform-origin: 0; } .mfp-arrow-right { -webkit-transform-origin: 100%; transform-origin: 100%; } .mfp-container { padding-left: 6px; padding-right: 6px; } } .mfp-ie7 .mfp-img { padding: 0; } .mfp-ie7 .mfp-bottom-bar { width: 600px; left: 50%; margin-left: -300px; margin-top: 5px; padding-bottom: 5px; } .mfp-ie7 .mfp-container { padding: 0; } .mfp-ie7 .mfp-content { padding-top: 44px; } .mfp-ie7 .mfp-close { top: 0; right: 0; padding-top: 0; } /* ------------------ HERO UNIT ------------------ */ .hero-unit { position: relative; height: 100%; } .hero-unit.hero-light .hero-content .hero-text .hero-heading, .hero-unit.hero-light .hero-content .hero-text p { color: #fff; } .hero-unit .hero-bg-pattern { filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=20); opacity: 0.2; width: 100%; height: 100%; background-image: url('../img/noise_lines_@2X.png?1342797527'); background-repeat: repeat; } .hero-unit .hero-content { position: absolute; left: 0; top: 50%; width: 100%; margin-top: -10em; z-index: 2; } @media screen and (max-width: 768px) { .hero-unit .hero-content { text-align: center; margin-top: -100px; } } @media screen and (min-width: 321px) and (max-width: 480px) { .hero-unit .hero-content { margin-top: -40px; } } @media screen and (max-width: 320px) { .hero-unit .hero-content { margin-top: -60px; } } .hero-unit .hero-content .hero-text .hero-heading, .hero-unit .hero-content .hero-text p { font-family: "Dosis", sans-serif; color: #fff; font-weight: 300; } .hero-unit .hero-content .hero-text .hero-heading { font-size: 5em; } .hero-unit .hero-content .hero-text .hero-heading .name { border-bottom: 2px solid #fff; } @media screen and (max-width: 768px) { .hero-unit .hero-content .hero-text .hero-heading { font-size: 4em; } } @media screen and (max-width: 480px) { .hero-unit .hero-content .hero-text .hero-heading { font-size: 2em; } } .hero-unit .hero-content .hero-text .looper { margin-top: 20px; } .hero-unit .hero-content .hero-text p { display: -moz-inline-stack; display: inline-block; vertical-align: middle; *vertical-align: auto; zoom: 1; *display: inline; font-size: 2em; color: #fff; padding: 0 10px; } @media screen and (max-width: 768px) { .hero-unit .hero-content .hero-text p { font-size: 1.5em; } } @media screen and (max-width: 480px) { .hero-unit .hero-content .hero-text p { font-size: 1.3em; } } .hero-unit .hero-content .hero-buttons { z-index: 2; } .hero-unit .hero-content .hero-buttons .btn { margin: 0 5px; font-weight: 400; } @media screen and (max-width: 480px) { .hero-unit .hero-content .hero-buttons .btn { margin-bottom: 10px; } } .hero-unit .hero-content .hero-buttons #btn-about { padding: 15px 41px; } .hero-unit .hero-content .hero-buttons #btn-contact { padding: 15px 30px; } @media screen and (max-width: 480px) { .hero-unit .hero-content .hero-buttons #btn-about, .hero-unit .hero-content .hero-buttons #btn-contact { padding: 5px 11px; } } .hero-unit .slide-caption { padding-bottom: 50px; margin: 0 auto; } @media screen and (max-width: 480px) { .hero-unit .slide-caption { padding-bottom: 0; } } .hero-unit .slideshow .slide-navigation #prevslide, .hero-unit .slideshow .slide-navigation #nextslide { -webkit-border-radius: 2px; -moz-border-radius: 2px; -ms-border-radius: 2px; -o-border-radius: 2px; border-radius: 2px; -webkit-transition-property: background; -moz-transition-property: background; -o-transition-property: background; transition-property: background; -webkit-transition-duration: 0.1s; -moz-transition-duration: 0.1s; -o-transition-duration: 0.1s; transition-duration: 0.1s; -webkit-transition-timing-function: linear; -moz-transition-timing-function: linear; -o-transition-timing-function: linear; transition-timing-function: linear; position: absolute; top: 50%; margin-top: -30px; width: 60px; height: 60px; background-color: rgba(255, 255, 255, 0.1); font-size: 3em; line-height: 1.2; color: #fff; text-align: center; cursor: pointer; z-index: 9; } .hero-unit .slideshow .slide-navigation #nextslide { right: 0; } .hero-unit .slideshow ul#slide-list { position: absolute; left: 50%; bottom: 40px; } @media screen and (max-width: 768px) { .hero-unit .slideshow ul#slide-list { display: none; } } .hero-unit .slideshow ul#slide-list li a { -webkit-border-radius: 15px; -moz-border-radius: 15px; -ms-border-radius: 15px; -o-border-radius: 15px; border-radius: 15px; -webkit-transition-property: background-color, border-color; -moz-transition-property: background-color, border-color; -o-transition-property: background-color, border-color; transition-property: background-color, border-color; -webkit-transition-duration: 0.2s; -moz-transition-duration: 0.2s; -o-transition-duration: 0.2s; transition-duration: 0.2s; -webkit-transition-timing-function: linear; -moz-transition-timing-function: linear; -o-transition-timing-function: linear; transition-timing-function: linear; display: block; width: 15px; height: 15px; text-indent: -9999px; border: 2px solid #fff; cursor: pointer; } .hero-unit .slideshow ul#slide-list li a:hover { background-color: #e6e6e6; } .hero-unit .slideshow ul#slide-list li.current-slide a { background-color: #e6e6e6; } .hero-unit #controls #pauseplay, .hero-unit #controls #video-volume { position: absolute; left: 50%; bottom: 30px; cursor: pointer; color: #fff; } .hero-unit #controls #pauseplay:hover, .hero-unit #controls #video-volume:hover { text-decoration: none; color: #e6e6e6; } .hero-unit #controls #pauseplay i, .hero-unit #controls #video-volume i { display: block; width: 10px; margin-left: -8px; } .hero-unit #controls #video-volume { z-index: 9999; } @media screen and (max-width: 768px) { .hero-unit #controls { display: none; } } /* the animation is taken form animate.css */ .looper.slide.down .item { -webkit-animation-name: slideInDown; animation-name: slideInDown; } .looper.slide.down .item.active.go { -webkit-animation-name: fadeOut; animation-name: fadeOut; } /* ------------------ ABOUT ------------------ */ .about { position: relative; text-align: center; } /* --------------------- */ /* SOCIAL NETWORK /* --------------------- */ #social-network { background-image: url('../img/sky.jpg?1394021998'); text-align: center; } #social-network h2 { color: #fff; font-size: 3em; } @media screen and (max-width: 480px) { #social-network h2 { font-size: 2em; } } .social-icon li { margin-left: 5px; margin-right: 5px; margin-top: 30px; } .social-icon li a { -webkit-border-radius: 50%; -moz-border-radius: 50%; -ms-border-radius: 50%; -o-border-radius: 50%; border-radius: 50%; -webkit-transition-property: background-color; -moz-transition-property: background-color; -o-transition-property: background-color; transition-property: background-color; -webkit-transition-duration: 0.2s; -moz-transition-duration: 0.2s; -o-transition-duration: 0.2s; transition-duration: 0.2s; -webkit-transition-timing-function: linear; -moz-transition-timing-function: linear; -o-transition-timing-function: linear; transition-timing-function: linear; display: block; width: 60px; height: 60px; font-size: 33px; line-height: 57px; text-align: center; color: #fff; border: 2px solid #fff; } .social-icon li a:hover { background-color: #fff; color: #00aeef; } @media screen and (max-width: 480px) { .social-icon { width: 100%; text-align: center; } .social-icon li { margin-left: 20px; margin-right: 20px; } } /* --------------------- */ /* SKILLS /* --------------------- */ .skills .skill-name { display: block; font-size: 1.5em; color: #ffae3f; font-weight: 400; } .chart { display: -moz-inline-stack; display: inline-block; vertical-align: middle; *vertical-align: auto; zoom: 1; *display: inline; position: relative; width: 150px; height: 150px; margin-bottom: 30px; } .chart canvas { position: absolute; top: 0; left: 0; } .chart .percent { display: -moz-inline-stack; display: inline-block; vertical-align: middle; *vertical-align: auto; zoom: 1; *display: inline; line-height: 150px; z-index: 2; font-family: "Dosis", sans-serif; font-size: 2em; color: #ffae3f; } .chart .percent:after { margin-left: 0.1em; } /* ------------------ SERVICES ------------------ */ .service-item { margin-bottom: 60px; } .service-item .service-icon { position: absolute; top: 0; font-size: 5em; color: #ffae3f; } .service-item .service-text { margin-left: 100px; overflow: hidden; } .service-item .service-text h3 { margin-top: 6px; color: #646464; } .service-item .service-text p { margin-bottom: 0; } .service-item .service-text a.read-more { color: #ffae3f; } .service-item .service-text a.read-more span { -webkit-transition-property: all; -moz-transition-property: all; -o-transition-property: all; transition-property: all; -webkit-transition-duration: 0.2s; -moz-transition-duration: 0.2s; -o-transition-duration: 0.2s; transition-duration: 0.2s; -webkit-transition-timing-function: linear; -moz-transition-timing-function: linear; -o-transition-timing-function: linear; transition-timing-function: linear; filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0); opacity: 0; font-size: 0.8em; margin-left: -80px; } @media screen and (max-width: 1200px) { .service-item .service-text a.read-more span { filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100); opacity: 1; margin-left: 0; } } .service-item .service-text a.read-more i { position: relative; top: 3px; font-size: 1em; } .service-item .service-text a.read-more:hover { text-decoration: none; } .service-item .service-text a.read-more:hover span { filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100); opacity: 1; margin-left: 0; } @media screen and (max-width: 480px) { .services { padding-bottom: 0; } } /* ------------------ WORKS ------------------ */ /* ----------------------------- */ /* RECOMMENDED ISOTOPE STYLES /* Has been ported into SASS /* ---------------------------- */ /* Isotope Filtering */ .isotope-item { z-index: 2; } .isotope-hidden.isotope-item { pointer-events: none; z-index: 1; } /* Isotope CSS3 transitions */ .isotope, .isotope .isotope-item { -webkit-transition-property: height, width; -moz-transition-property: height, width; -o-transition-property: height, width; transition-property: height, width; } .isotope, .isotope .isotope-item { -webkit-transition-duration: 0.4s; -moz-transition-duration: 0.4s; -o-transition-duration: 0.4s; transition-duration: 0.4s; } .isotope .isotope-item { -webkit-transition-property: -webkit-transform, opacity; -moz-transition-property: -moz-transform, opacity; -o-transition-property: -o-transform, opacity; transition-property: transform, opacity; } /* disabling Isotope CSS3 transitions */ .isotope.no-transition, .isotope .no-transition.isotope-item, .isotope.no-transition .isotope-item, .isotope .no-transition.isotope-item .isotope-item, .isotope .isotope-item.no-transition { -webkit-transition-duration: 0s; -moz-transition-duration: 0s; -o-transition-duration: 0s; transition-duration: 0s; } /* --------------------- */ /* WORKS GRID /* --------------------- */ #works { padding-bottom: 0; } .work-item-filters { text-align: center; margin-bottom: 0; background-color: #e2e2e2; } .work-item-filters li { padding: 0; margin-left: -2px; margin-right: -2px; } .work-item-filters li:first-child { margin-left: 0; } .work-item-filters li a { display: block; padding: 15px; color: #9a9a9a; } .work-item-filters li a:hover, .work-item-filters li a.active { text-decoration: none; outline: none; background-color: #ffae3f; color: #fff; } .work-item-wrapper { overflow: hidden; } .work-item-list { margin-bottom: 0; width: 101%; } .work-item-list li { padding: 0; float: left; overflow: hidden; position: relative; } .work-item-list li img { -webkit-transition-property: all; -moz-transition-property: all; -o-transition-property: all; transition-property: all; -webkit-transition-duration: 0.2s; -moz-transition-duration: 0.2s; -o-transition-duration: 0.2s; transition-duration: 0.2s; -webkit-transition-timing-function: linear; -moz-transition-timing-function: linear; -o-transition-timing-function: linear; transition-timing-function: linear; max-width: 100%; width: 100%; } .work-item-list li:hover img { -webkit-transform: scale(1.3, 1.3); -moz-transform: scale(1.3, 1.3); -ms-transform: scale(1.3, 1.3); -o-transform: scale(1.3, 1.3); transform: scale(1.3, 1.3); } .work-item-list.list-col-5 li { width: 19.95%; } .work-item-list.list-col-4 li { width: 24.90%; } .work-item-list.list-col-3 li { width: 33.32%; } .work-item-list.list-col-2 li { width: 49.90%; } @media screen and (max-width: 548px) { .work-item-list.list-col-2 li, .work-item-list.list-col-3 li, .work-item-list.list-col-4 li, .work-item-list.list-col-5 li { width: 100%; } } @media screen and (min-width: 548px) and (max-width: 1024px) { .work-item-list.list-col-2 li, .work-item-list.list-col-3 li, .work-item-list.list-col-4 li, .work-item-list.list-col-5 li { width: 49.90%; } } .work-item-list .image-overlay { filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0); opacity: 0; -webkit-transition-property: opacity; -moz-transition-property: opacity; -o-transition-property: opacity; transition-property: opacity; -webkit-transition-duration: 0.2s; -moz-transition-duration: 0.2s; -o-transition-duration: 0.2s; transition-duration: 0.2s; -webkit-transition-timing-function: linear; -moz-transition-timing-function: linear; -o-transition-timing-function: linear; transition-timing-function: linear; position: absolute; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0, 174, 239, 0.9); } .work-item-list .image-overlay:hover { filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100); opacity: 1; } @media screen and (max-width: 1024px) { .work-item-list .image-overlay { filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100); opacity: 1; top: initial; bottom: 0; height: 30%; } } .work-item-list .image-overlay a { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } @media screen and (max-width: 1024px) { .work-item-list .image-overlay a:not(.mfp-iframe) { pointer-events: none; cursor: default; } } .work-item-list .work-item-info { position: absolute; left: 0; bottom: 50%; margin-bottom: -2.5em; width: 100%; text-align: center; color: #fff; } .work-item-list .work-item-info i { filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=20); opacity: 0.2; font-size: 96px; position: absolute; left: 50%; margin-left: -48px; top: 50%; margin-top: -48px; } @media screen and (max-width: 1024px) { .work-item-list .work-item-info i { display: none; } } .work-item-list .work-item-info h3 { color: #fff; } @media screen and (min-width: 548px) and (max-width: 1024px) { .work-item-list .work-item-info h3 { font-size: 1.3em; line-height: 8px; } .work-item-list .work-item-info p { font-size: 0.8em; } } /* --------------------- */ /* POPUP /* --------------------- */ button.mfp-close, .mfp-image-holder .mfp-close, .mfp-iframe-holder .mfp-close, .mfp-close { font-size: 23px; width: 36px; background: rgba(0, 0, 0, 0.5); height: 36px; top: 0; right: 0; text-align: center; padding-right: 0; display: inline; font-family: inherit; line-height: 1; } .mfp-zoom-out-cur .mfp-image-holder .mfp-close { cursor: pointer; } .mfp-bottom-bar { padding: 10px; background: rgba(0, 0, 0, 0.7); top: 90%; height: 100%; } .mfp-bottom-bar h3 { color: #fff; } .mfp-bottom-bar p { font-size: 0.9em; } img.mfp-img { padding: 0; } .mfp-figure { position: relative; margin: 0 40px 0 40px; overflow: hidden; } /* fade animation */ .mfp-fade { /* content at start */ } .mfp-fade.mfp-bg { filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0); opacity: 0; -webkit-transition-property: all; -moz-transition-property: all; -o-transition-property: all; transition-property: all; -webkit-transition-duration: 0.15s; -moz-transition-duration: 0.15s; -o-transition-duration: 0.15s; transition-duration: 0.15s; -webkit-transition-timing-function: ease-out; -moz-transition-timing-function: ease-out; -o-transition-timing-function: ease-out; transition-timing-function: ease-out; /* overlay animate in */ /* overlay animate out */ } .mfp-fade.mfp-bg.mfp-ready { filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=80); opacity: 0.8; } .mfp-fade.mfp-bg.mfp-removing { filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0); opacity: 0; } .mfp-fade.mfp-wrap { /* content animate it */ /* content animate out */ } .mfp-fade.mfp-wrap .mfp-content { filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0); opacity: 0; -webkit-transition-property: all; -moz-transition-property: all; -o-transition-property: all; transition-property: all; -webkit-transition-duration: 0.15s; -moz-transition-duration: 0.15s; -o-transition-duration: 0.15s; transition-duration: 0.15s; -webkit-transition-timing-function: ease-out; -moz-transition-timing-function: ease-out; -o-transition-timing-function: ease-out; transition-timing-function: ease-out; } .mfp-fade.mfp-wrap.mfp-ready .mfp-content { filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100); opacity: 1; } .mfp-fade.mfp-wrap.mfp-removing .mfp-content { filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0); opacity: 0; } /* ------------------ CONTACT ------------------ */ /* --------------------- */ /* CONTACT INFO /* --------------------- */ .contact-info li { padding-bottom: 30px; } .contact-info h3, .contact-info i { color: #646464; } .contact-info h3, .contact-info p { padding-left: 52px; } .contact-info p { font-size: 14px; } .contact-info i { font-size: 40px; } @media screen and (max-width: 768px) { .contact-info { text-align: center; } .contact-info i { width: 100%; } .contact-info h3, .contact-info p { padding-left: 0; } } @media screen and (max-width: 480px) { .contact { padding-bottom: 0; } } /* --------------------- */ /* CONTACT FORM /* --------------------- */ .contact-form { overflow: hidden; margin-bottom: 40px; } .contact-form input[type="text"], .contact-form input[type="email"], .contact-form textarea { display: -moz-inline-stack; display: inline-block; vertical-align: middle; *vertical-align: auto; zoom: 1; *display: inline; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; padding: 12px; margin-bottom: 7px; min-height: 3em; border: none; background-color: #f2f2f2; } .contact-form .form-group { margin-bottom: 0; } .contact-form textarea { width: 100%; display: block; padding: 14px; min-height: 130px; } .contact-form input[type="text"], .contact-form input[type="email"], .contact-form textarea { -webkit-border-radius: 3px; -moz-border-radius: 3px; -ms-border-radius: 3px; -o-border-radius: 3px; border-radius: 3px; -webkit-box-shadow: none !important; -moz-box-shadow: none !important; box-shadow: none !important; } .contact-form input[type="text"]:focus, .contact-form input[type="email"]:focus, .contact-form textarea:focus { outline: none; } .contact-form .alert, .contact-form label { display: none; } @media screen and (max-width: 480px) { .contact-form .btn-primary { width: 100%; } } /* ------------------ TWITTER STREAM ------------------ */ .twitter-stream { text-align: center; padding: 40px 0; background-color: #00aeef; } @media screen and (max-width: 480px) { .twitter-stream { padding: 25px 0; } } .twitter-stream .twitter-icon { -webkit-border-radius: 50%; -moz-border-radius: 50%; -ms-border-radius: 50%; -o-border-radius: 50%; border-radius: 50%; display: -moz-inline-stack; display: inline-block; vertical-align: middle; *vertical-align: auto; zoom: 1; *display: inline; width: 50px; height: 50px; margin-bottom: 20px; background-color: #00a6e7; } .twitter-stream .twitter-icon i { font-size: 30px; line-height: 50px; color: #36c3ff; } .twitter-stream #tweet ul { list-style-type: none; } .twitter-stream #tweet ul li { color: #fff; } .twitter-stream #tweet ul li a { text-decoration: underline; color: #fff; text-overflow: ellipsis; } .twitter-stream #tweet ul li a span { word-wrap: break-word; } .twitter-stream #tweet ul li a:hover { text-decoration: none; } .twitter-stream #tweet ul li .timePosted { font-size: 0.8em; } /* ------------------ FOOTER ------------------ */ #footer { padding-top: 20px; padding-bottom: 10px; } .back-to-top { display: none; position: fixed; right: 10px; bottom: 10px; z-index: 9999; } @media screen and (max-width: 992px) { .back-to-top { display: none !important; } .skills .skill-name { margin-bottom: 2em; } } .back-to-top a { -webkit-border-radius: 2px; -moz-border-radius: 2px; -ms-border-radius: 2px; -o-border-radius: 2px; border-radius: 2px; -webkit-transition-property: background-color; -moz-transition-property: background-color; -o-transition-property: background-color; transition-property: background-color; -webkit-transition-duration: 0.2s; -moz-transition-duration: 0.2s; -o-transition-duration: 0.2s; transition-duration: 0.2s; -webkit-transition-timing-function: linear; -moz-transition-timing-function: linear; -o-transition-timing-function: linear; transition-timing-function: linear; display: block; width: 25px; height: 25px; color: #fff; text-align: center; background-color: rgba(0, 0, 0, 0.3); } .back-to-top a:hover { background-color: rgba(0, 0, 0, 0.5); } .copyright { font-size: 0.8em; line-height: 36px; } @media screen and (max-width: 480px) { .copyright { width: 100%; text-align: center; } }
mazhar266/mazhar266.github.io
new/assets/css/main.css
CSS
gpl-2.0
144,320
package com.example.shokedbrain.usus; /** * Created by shokedbrain on 05.06.17. */ public class Room { private String roomName; public Room() { } public Room(String roomName) { this.roomName = roomName; } public String getRoomName() { return roomName; } public void setRoomName(String roomName) { this.roomName = roomName; } }
Macleopard/Usus
app/src/main/java/com/example/shokedbrain/usus/Room.java
Java
gpl-2.0
395
package com.xiner.game.util; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.xiner.game.ball.LotteryBox; import com.xiner.game.ball.LotteryStage; import com.xiner.game.ball.LotteryStatistic; import com.xiner.game.ball.LotteryContain; import com.xiner.game.data.CommonData; /** * https://dl-ssl.google.com/android/eclipse/ * @author xiner * */ public class LotteryManager { static LotteryManager m_LotteryManager = null; /** * key: lottery flag name * value: lottery content */ private Map<String, LotteryContain> m_Lottery = null; /** * key: statistic flag name * value: lottery statistic */ private Map<String, LotteryStatistic> m_Statistic = null; private String m_KEY_Lottery; private String m_KEY_Statistic; public LotteryManager() { m_LotteryManager = this; m_Lottery = new HashMap<String, LotteryContain>(); m_Statistic = new HashMap<String, LotteryStatistic>(); } public static void create() { if (m_LotteryManager == null) { m_LotteryManager = new LotteryManager(); } } /** * * @return */ public static LotteryManager getInstance() { if (m_LotteryManager == null) { m_LotteryManager = new LotteryManager(); } return m_LotteryManager; } public String getKEY_Lottery() { if (m_KEY_Lottery == null || "".equals(m_KEY_Lottery)) { m_KEY_Lottery = CommonData.KEY_Lottery_AnalysisHTML; } return m_KEY_Lottery; } public void setKEY_Lottery(String KEY_Lottery) { this.m_KEY_Lottery = KEY_Lottery; } public String getKEY_Statistic() { if (m_KEY_Statistic == null || "".equals(m_KEY_Statistic)) { m_KEY_Statistic = CommonData.KEY_Statistic_TEMP; } return m_KEY_Statistic; } public void setKEY_Statistic(String KEY_Statistic) { this.m_KEY_Statistic = KEY_Statistic; } /** * add lottery stage * @param lotteryKey: lottery flag key * @param lotteryStage: lottery stage */ public void addLotteryStage(String lotteryKey, LotteryStage lotteryStage) { LotteryContain lotteryContain = getLotteryContain(lotteryKey); lotteryContain.addLotteryStage(lotteryStage); } /** * get lotteryContain by lottery flag key * @param lotteryKey: lottery flag key * @return */ public LotteryContain getLotteryContain(String lotteryKey) { LotteryContain lotteryContain = null; lotteryContain = m_Lottery.get(lotteryKey); if (lotteryContain == null) { lotteryContain = new LotteryContain(); m_Lottery.put(lotteryKey, lotteryContain); } return lotteryContain; } public LotteryStage getLastLotteryStage(String lotteryKey) { LotteryStage lotteryStage = null; LotteryContain lotteryContain = getLotteryContain(lotteryKey); if (lotteryContain != null) { Map<Integer, LotteryBox> boxmap = lotteryContain.getLotteryContain(); int year = 0; for (LotteryBox box : boxmap.values()) { int y = Integer.parseInt(box.getYear()); if (y > year) { year = y; } } LotteryBox box = boxmap.get(new Integer(year)); List<Entry<String, LotteryStage>> list = box.getLotteryBoxByOrder(); lotteryStage = list.get(list.size()-1).getValue(); } return lotteryStage; } /** * source lottery add to traget lottery * @param skey: source flag key * @param tKey: traget flag key */ public void addSource2Target(String skey, String tKey) { LotteryContain sContain = getLotteryContain(skey); LotteryContain tContain = getLotteryContain(tKey); tContain.addLotteryContain(sContain); } /** * clear lotterContain by key * @param key: lotteryContain flag name */ public void clearContain(String key) { LotteryContain lotteryContain = getLotteryContain(key); lotteryContain.getLotteryContain().clear(); } /** * add lottery statistic * @param key: statistic flag name * @param lotteryStatistic: lotteryStatistic */ public void putLotteryStatistic(String key, LotteryStatistic lotteryStatistic) { LotteryStatistic lStatistic = getLotteryStatistic(key, false); if (lStatistic != null) { m_Statistic.remove(key); } m_Statistic.put(key, lotteryStatistic); } /** * get lotteryStatistic * @param key: statistic flag name * @param isAdd: ture -if null and add one * @return: lotteryStatistic */ public LotteryStatistic getLotteryStatistic(String key, boolean isAdd) { LotteryStatistic lotteryStatistic = null; lotteryStatistic = m_Statistic.get(key); if (isAdd && lotteryStatistic == null) { lotteryStatistic = new LotteryStatistic(); m_Statistic.put(key, lotteryStatistic); } return lotteryStatistic; } /** * clear lotteryStatistic by key * @param key: lotteryStatistic flag name */ public void clearStatistic(String key) { LotteryStatistic lotteryStatistic = getLotteryStatistic(key, false); if (lotteryStatistic != null) { lotteryStatistic.clear(); } } /** * lotteryCotain change to lotteryStatistic * @param lotteryContain: lotteryContain * @param lotteryStatistic: lotteryStatistic */ public void lotteryContain2Statistic(LotteryContain lotteryContain, LotteryStatistic lotteryStatistic) { List<Entry<Integer, LotteryBox>> boxList = lotteryContain.getLotteryContainByOrder(); for (Entry<Integer, LotteryBox> entryBox : boxList) { LotteryBox lotteryBox = entryBox.getValue(); lotteryBox2Statistic(lotteryBox, lotteryStatistic); } } /** * lotteryBox change to lotteryStatistic * @param lotteryBox: lotteryBox * @param lotteryStatistic: lotteryStatistic */ public void lotteryBox2Statistic(LotteryBox lotteryBox, LotteryStatistic lotteryStatistic) { List<Entry<String, LotteryStage>> stageList = lotteryBox.getLotteryBoxByOrder(); for (Entry<String, LotteryStage> entryStage : stageList) { LotteryStage lotteryStage = entryStage.getValue(); lotteryStage2Statistic(lotteryStage, lotteryStatistic); } } /** * lotteryStage change to lotteryStatistic * @param lotteryStage: lotteryStage * @param lotteryStatistic: lotteryStatistic */ public void lotteryStage2Statistic(LotteryStage lotteryStage, LotteryStatistic lotteryStatistic) { lotteryStatistic.updateByLotteryStage(lotteryStage); } }
xinerworld/ProbabilityGame
src/com/xiner/game/util/LotteryManager.java
Java
gpl-2.0
6,443
using System.Collections.Generic; using System.IO; using Transformer.Core.Logging; using Transformer.Core.Model; namespace Transformer.Core.Template { public class TemplateEngine { private static readonly ILog Log = LogManager.GetLogger(typeof(VariableResolver)); public VariableResolver VariableResolver { get; set; } public int TransformDirectory(string path, Environment targetEnvironment, string subEnvironment = null, bool deleteTemplate = true) { if (subEnvironment == null) subEnvironment = string.Empty; Log.InfoFormat("Transform templates for environment {1} in {0} {2} deleting templates", path, targetEnvironment.Name, deleteTemplate ? "with" : "without"); targetEnvironment.Variables.Add(new Variable() { Name = "subenv", Value = subEnvironment }); VariableResolver = new VariableResolver(targetEnvironment.Variables); int templateCounter = 0; foreach (var templateFile in Directory.EnumerateFiles(path, "*.template.*", SearchOption.AllDirectories)) { ++templateCounter; Log.Info(string.Format(" Transform template {0}", templateFile)); var templateText = File.ReadAllText(templateFile); var transformed = VariableResolver.TransformVariables(templateText); ConvertTemplateNameToTargetName(templateFile).OverwriteContent(transformed); if (deleteTemplate) { File.Delete(templateFile); } } Log.InfoFormat("Transformed {0} template(s) in {1}.", templateCounter, path); return templateCounter; } private string ConvertTemplateNameToTargetName(string templateName) { return templateName.Replace(".template.", ".").Replace(".Template.", "."); } } public class TransformResult { public int TransformedVariables { get; set; } public List<string> MissingVariables { get; set; } } }
tobiaszuercher/transformer
src/Transformer.Core/Template/TemplateEngine.cs
C#
gpl-2.0
2,109
/* * Common DPS routines * dps.h * Provides common structure definitions and routines for all applications * * Copyright (c) 2005-2006 Chris Cantwell * * 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 "dps.h" #include "Logger.h" #include <iostream> #include <sstream> #include <cstdlib> using std::endl; #include <pqxx/pqxx> track dps_getTrack(std::string md5) { const char *routine = "dps::dps_getTrack"; DataAccess DB; track t; t.isNull = true; PqxxResult R; std::string SQL, type; try { SQL = "SELECT audiotypes.name AS type " "FROM audio,audiotypes " "WHERE audiotypes.id = audio.type " "AND md5='" + md5 + "'"; type = DB.exec("DpsGetTrack",SQL)[0]["type"].c_str(); } catch (...) { L_ERROR(LOG_DB, "Cannot get track " + md5); return t; } if (type == "music") { try { SQL = "SELECT audio.md5 AS md5, audio.title AS title, " "artists.name AS artist, albums.name AS album, " "archives.name AS archive, audio.music_track AS track, " "audio.music_released AS released, " "audio.length_smpl AS length, audio.start_smpl AS start, " "audio.end_smpl AS end, audio.intro_smpl AS fade_in, " "audio.extro_smpl AS fade_out, audio.censor AS censor " "FROM audio, audioartists, artists, albums, archives " "WHERE audioartists.audio = audio.id " "AND audioartists.artist = artists.id " "AND audio.archive = archives.id " "AND audio.music_album = albums.id " "AND audio.md5 = '" + md5 + "' " "ORDER BY audio.md5"; R = DB.exec("DpsGetTrack",SQL); } catch (...) { L_ERROR(LOG_DB, "SQL failed on getTrack."); L_ERROR(LOG_DB, " -> SQL: " + SQL ); } if (R.size() > 0) { t.md5 = R[0]["md5"].c_str(); t.title = R[0]["title"].c_str(); t.artists.push_back(R[0]["artist"].c_str()); t.album = R[0]["album"].c_str(); t.release_date = R[0]["released"].c_str(); t.tracknum = atoi(R[0]["track"].c_str()); if (std::string(R[0]["censor"].c_str()) == "t") t.censor = true; else t.censor = false; t.length_smpl = atoi(R[0]["length"].c_str()); t.trim_start_smpl = atoi(R[0]["start"].c_str()); t.trim_end_smpl = atoi(R[0]["end"].c_str()); t.fade_in_smpl = atoi(R[0]["fade_in"].c_str()); t.fade_out_smpl = atoi(R[0]["fade_out"].c_str()); t.isNull = false; } } if (type == "jingle") { try { SQL = "SELECT audio.md5 AS md5, audio.title AS title, " "albums.name AS album, " "archives.name AS archive, audio.music_track AS track, " "audio.length_smpl AS length, audio.start_smpl AS start, " "audio.end_smpl AS end, audio.intro_smpl AS fade_in, " "audio.extro_smpl AS fade_out, audio.censor AS censor " "FROM audio, archives, albums " "WHERE audio.archive = archives.id " "AND audio.music_album = albums.id " "AND audio.md5 = '" + md5 + "' " "ORDER BY audio.md5"; R = DB.exec("DpsGetTrack", SQL); } catch (...) { L_ERROR(LOG_DB, "SQL failed on getTrack."); L_ERROR(LOG_DB, " -> SQL: " + SQL); } if (R.size() > 0) { t.md5 = R[0]["md5"].c_str(); t.title = R[0]["title"].c_str(); t.album = R[0]["album"].c_str(); t.length_smpl = atoi(R[0]["length"].c_str()); t.trim_start_smpl = atoi(R[0]["start"].c_str()); t.trim_end_smpl = atoi(R[0]["end"].c_str()); t.fade_in_smpl = atoi(R[0]["fade_in"].c_str()); t.fade_out_smpl = atoi(R[0]["fade_out"].c_str()); t.isNull = false; } } DB.abort("DpsGetTrack"); return t; } std::string dps_itoa(long num) { std::stringstream S (std::stringstream::in | std::stringstream::out); S << num; return S.str(); } std::string& dps_strTrim(std::string& s) { std::string::size_type pos = s.find_last_not_of(' '); if (pos != std::string::npos) { s.erase(pos + 1); pos = s.find_first_not_of(' '); if (pos != std::string::npos) s.erase(0,pos); } else { s.erase(s.begin(), s.end()); } return s; } // TODO: replace users of this function with stdlib version std::string& dps_strLcase(std::string& s) { for (unsigned int i = 0; i < s.length(); i++) { if (s[i] >= 'A' && s[i] <= 'Z') s[i] = s[i] + 32; } return s; } std::string dps_strPcase(std::string *Str) { bool upper = true; bool punctuate = false; if (Str->length() < 1) return *Str; for (unsigned int i = 0; i < Str->length() - 1; i++) { char now = (*Str)[i]; char next = (*Str)[i]; if ((now == '.' || now == ',' || now == '?') && next == ' ') { punctuate = true; upper = true; continue; } if ((now == '(' || now == '\'' || now == '\"') && (i == 0 || (*Str)[i-1] == ' ')) { upper = true; continue; } if ((punctuate) && now != ' ') { Str->insert(i+1,1,' '); punctuate = false; continue; } if (now == ' ') { upper = true; continue; } if (upper) { if (now >= 'a' && now <= 'z') (*Str)[i] = (*Str)[i] - 32; upper = false; } else { if (now >= 'A' && now <= 'Z') (*Str)[i] = (*Str)[i] + 32; } } if ((*Str)[Str->length() - 1] >= 'A' && (*Str)[Str->length() - 1] <= 'Z') (*Str)[Str->length() - 1] = (*Str)[Str->length() - 1] + 32; return *Str; } std::string dps_strNum(long num, unsigned int digits) { std::string result = dps_itoa(num); for (unsigned int i = 1; i < digits; i++) { if (result.length() < digits) { result = "0" + result; } } return result; } std::string dps_prettyTime(long samples) { std::string result = ""; int hours = (int)(samples / 158760000); if (hours > 0) { result += dps_itoa(hours) + "h "; } samples -= hours*158760000; int mins = (int)(samples / 2646000); if (mins > 0) { if (mins < 10) { result += "0"; } result += dps_itoa(mins) + "m "; } samples -= mins*2646000; int secs = (int)(samples / 44100); if (secs < 10) { result += "0"; } result += dps_itoa(secs) + "."; samples -= secs*44100; int ms = (int)(samples / 441); if (ms < 10) { result += "0"; } result += dps_itoa(ms) + "s"; return result; } long dps_current_time() { return (long)time(NULL); }
radiowarwick/digiplay_legacy
src/dps.cpp
C++
gpl-2.0
7,399