answer
stringlengths
15
1.25M
#ifndef __QD3DSHADER__ #define __QD3DSHADER__ #ifndef __QD3D__ #include "QD3D.h" #endif #ifndef __MOVIES__ #include "Movies.h" #endif #if PRAGMA_ONCE #pragma once #endif #ifdef __cplusplus extern "C" { #endif #if PRAGMA_IMPORT #pragma import on #endif #if PRAGMA_STRUCT_ALIGN #pragma options align=power #elif <API key> #pragma pack(push, 2) #elif PRAGMA_STRUCT_PACK #pragma pack(2) #endif #if <API key> #if defined(__fourbyteints__) && !__fourbyteints__ #define <API key> #pragma fourbyteints on #endif #pragma enumsalwaysint on #elif PRAGMA_ENUM_OPTIONS #pragma option enum=int #elif PRAGMA_ENUM_PACK #if __option(pack_enums) #define <API key> #pragma options(!pack_enums) #endif #endif #if CALL_NOT_IN_CARBON EXTERN_API_C( TQ3ColorRGB *) Q3ColorRGB_Set (TQ3ColorRGB * color, float r, float g, float b); EXTERN_API_C( TQ3ColorARGB *) Q3ColorARGB_Set (TQ3ColorARGB * color, float a, float r, float g, float b); EXTERN_API_C( TQ3ColorRGB *) Q3ColorRGB_Add (const TQ3ColorRGB * c1, const TQ3ColorRGB * c2, TQ3ColorRGB * result); EXTERN_API_C( TQ3ColorRGB *) Q3ColorRGB_Subtract (const TQ3ColorRGB * c1, const TQ3ColorRGB * c2, TQ3ColorRGB * result); EXTERN_API_C( TQ3ColorRGB *) Q3ColorRGB_Scale (const TQ3ColorRGB * color, float scale, TQ3ColorRGB * result); EXTERN_API_C( TQ3ColorRGB *) Q3ColorRGB_Clamp (const TQ3ColorRGB * color, TQ3ColorRGB * result); EXTERN_API_C( TQ3ColorRGB *) Q3ColorRGB_Lerp (const TQ3ColorRGB * first, const TQ3ColorRGB * last, float alpha, TQ3ColorRGB * result); EXTERN_API_C( TQ3ColorRGB *) <API key> (const TQ3ColorRGB * src, TQ3ColorRGB * result); #endif /* CALL_NOT_IN_CARBON */ #if CALL_NOT_IN_CARBON EXTERN_API_C( float *) <API key> (const TQ3ColorRGB * color, float * luminance); #endif /* CALL_NOT_IN_CARBON */ enum TQ3ShaderUVBoundary { <API key> = 0, <API key> = 1 }; typedef enum TQ3ShaderUVBoundary TQ3ShaderUVBoundary; #if CALL_NOT_IN_CARBON EXTERN_API_C( TQ3ObjectType ) Q3Shader_GetType (TQ3ShaderObject shader); EXTERN_API_C( TQ3Status ) Q3Shader_Submit (TQ3ShaderObject shader, TQ3ViewObject view); EXTERN_API_C( TQ3Status ) <API key> (TQ3ShaderObject shader, const TQ3Matrix3x3 * uvTransform); EXTERN_API_C( TQ3Status ) <API key> (TQ3ShaderObject shader, TQ3Matrix3x3 * uvTransform); EXTERN_API_C( TQ3Status ) <API key> (TQ3ShaderObject shader, TQ3ShaderUVBoundary uBoundary); EXTERN_API_C( TQ3Status ) <API key> (TQ3ShaderObject shader, TQ3ShaderUVBoundary vBoundary); EXTERN_API_C( TQ3Status ) <API key> (TQ3ShaderObject shader, TQ3ShaderUVBoundary * uBoundary); EXTERN_API_C( TQ3Status ) <API key> (TQ3ShaderObject shader, TQ3ShaderUVBoundary * vBoundary); EXTERN_API_C( TQ3ObjectType ) <API key> (TQ3ShaderObject shader); EXTERN_API_C( TQ3ShaderObject ) <API key> (void); EXTERN_API_C( TQ3ShaderObject ) <API key> (void); EXTERN_API_C( TQ3ShaderObject ) <API key> (void); EXTERN_API_C( TQ3ObjectType ) <API key> (<API key> shader); EXTERN_API_C( TQ3ShaderObject ) Q3TextureShader_New (TQ3TextureObject texture); EXTERN_API_C( TQ3Status ) <API key> (TQ3ShaderObject shader, TQ3TextureObject * texture); EXTERN_API_C( TQ3Status ) <API key> (TQ3ShaderObject shader, TQ3TextureObject texture); EXTERN_API_C( TQ3ObjectType ) Q3Texture_GetType (TQ3TextureObject texture); EXTERN_API_C( TQ3Status ) Q3Texture_GetWidth (TQ3TextureObject texture, unsigned long * width); EXTERN_API_C( TQ3Status ) Q3Texture_GetHeight (TQ3TextureObject texture, unsigned long * height); EXTERN_API_C( TQ3TextureObject ) Q3PixmapTexture_New (const TQ3StoragePixmap * pixmap); EXTERN_API_C( TQ3Status ) <API key> (TQ3TextureObject texture, TQ3StoragePixmap * pixmap); EXTERN_API_C( TQ3Status ) <API key> (TQ3TextureObject texture, const TQ3StoragePixmap * pixmap); EXTERN_API_C( TQ3TextureObject ) Q3MipmapTexture_New (const TQ3Mipmap * mipmap); EXTERN_API_C( TQ3Status ) <API key> (TQ3TextureObject texture, TQ3Mipmap * mipmap); EXTERN_API_C( TQ3Status ) <API key> (TQ3TextureObject texture, const TQ3Mipmap * mipmap); EXTERN_API_C( TQ3TextureObject ) <API key> (const TQ3CompressedPixmap * compressedPixmap); EXTERN_API_C( TQ3Status ) <API key> (TQ3TextureObject texture, TQ3CompressedPixmap * compressedPixmap); EXTERN_API_C( TQ3Status ) <API key> (TQ3TextureObject texture, const TQ3CompressedPixmap * compressedPixmap); EXTERN_API_C( TQ3Status ) <API key> (TQ3CompressedPixmap * compressedPixmap, PixMapHandle sourcePixMap, CodecType codecType, CodecComponent codecComponent, short codedDepth, CodecQ codecQuality); #endif /* CALL_NOT_IN_CARBON */ #if <API key> #pragma enumsalwaysint reset #ifdef <API key> #pragma fourbyteints off #endif #elif PRAGMA_ENUM_OPTIONS #pragma option enum=reset #elif defined(<API key>) #pragma options(pack_enums) #endif #if PRAGMA_STRUCT_ALIGN #pragma options align=reset #elif <API key> #pragma pack(pop) #elif PRAGMA_STRUCT_PACK #pragma pack() #endif #ifdef PRAGMA_IMPORT_OFF #pragma import off #elif PRAGMA_IMPORT #pragma import reset #endif #ifdef __cplusplus } #endif #endif /* __QD3DSHADER__ */
#include <rtthread.h> #include "tc_comm.h" static struct rt_thread thread1; static rt_uint8_t thread1_stack[THREAD_STACK_SIZE]; static struct rt_thread thread2; static rt_uint8_t thread2_stack[THREAD_STACK_SIZE]; static void thread1_entry(void* parameter) { rt_uint32_t count = 0; while (1) { rt_kprintf("thread count: %d\n", count ++); } } static void thread2_entry(void* parameter) { /* 210OS Tick */ rt_thread_delay(10); /* * 211 */ rt_thread_detach(&thread1); /* * 210OS Tick */ rt_thread_delay(10); } int thread_detach_init() { rt_err_t result; result = rt_thread_init(&thread1, "t1", thread1_entry, RT_NULL, /* thread1_entryRT_NULL*/ &thread1_stack[0], sizeof(thread1_stack), /* thread1_stack */ THREAD_PRIORITY, 10); if (result == RT_EOK) rt_thread_startup(&thread1); else tc_stat(TC_STAT_END | TC_STAT_FAILED); result = rt_thread_init(&thread2, "t2", thread2_entry, RT_NULL, /* thread2_entryRT_NULL*/ &thread2_stack[0], sizeof(thread2_stack), /* thread2_stack */ THREAD_PRIORITY - 1, 10); if (result == RT_EOK) rt_thread_startup(&thread2); else tc_stat(TC_STAT_END | TC_STAT_FAILED); return 0; } #ifdef RT_USING_TC static void _tc_cleanup() { rt_enter_critical(); if (thread1.stat != RT_THREAD_CLOSE) rt_thread_detach(&thread1); if (thread2.stat != RT_THREAD_CLOSE) rt_thread_detach(&thread2); rt_exit_critical(); /* TestCase */ tc_done(TC_STAT_PASSED); } int _tc_thread_detach() { /* TestCase */ tc_cleanup(_tc_cleanup); thread_detach_init(); /* TestCase */ return 100; } /* finsh shell */ <API key>(_tc_thread_detach, a static thread example); #else int rt_application_init() { thread_detach_init(); return 0; } #endif
{config_load file="$language/lang_$language.conf" section="<API key>"} <h1>{#heading_address#}</h1> {$FORM_ACTION} {if $error != ''}<div class="errormessage">{$error}</div>{/if} <p>{#<API key>#}</p> <p><strong>{#<API key>#}:</strong><br />{$ADDRESS_LABEL}</p> {if $BLOCK_ADDRESS} <h1>{#title_old_addresses#}</h1> <p>{#text_old_addresses#}</p> <p>{$BLOCK_ADDRESS}</p> {/if} {if $MODULE_new_address} {$MODULE_new_address} {/if} <p>{$BUTTON_BACK}&nbsp;{$BUTTON_CONTINUE}</p> {$FORM_END}
<?php module_head("Links to other develoment tools");?> <br> <h4>Ambienti di Sviluppo Integrati (IDE)</h4> <table width="100%" border=0 cellspacing=2 cellpadding=2> <tr align=left> <th class=header>Link</th> <th class=header width="100%">Commento</th> </tr> <tr valign=top> <td class=even><a HREF="http: <td class=even>Un aperto e estensibile per fare un pò di tutto</td> </tr> <tr valign=top> <td class=odd><a HREF="http: <td class=odd>Un IDE OpenSource IDE della New Planet Software</td> </tr> <tr valign=top> <td class=even><a HREF="http://vdkbuilder.sourceforge.net/">VDK Builder</a></td> <td class=even>uno strumento RAD (Rapid Application Development) basato su VDK</td> </tr> <tr valign=top> <td class=odd><a HREF="http://primates.ximian.com/~jpr/gide/">gIDE</a></td> <td class=odd>per sviluppo C/GNOME (Anjuta sembra sostituire gIDE)</td> </tr> <tr valign=top> <td class=even><a HREF="http: <td class=even>un IDE per C/C++ su GNU/Linux. Riscritto per GTK/GNOME</td> </tr> <tr valign=top> <td class=odd><a HREF="http: <td class=odd>un IDE per DJGPP a per altri sistemi GNU</td> </tr> <tr valign=top> <td class=even><a HREF="http: <td class=even>un ambiente di programmazione per sistemi UNIX</td> </tr> <tr valign=top> <td class=odd><a HREF="http://wxstudio.sourceforge.net/">wxstudio</a></td> <td class=odd>un ambiente di sviluppo integrato cross-platform</td> </tr> <tr valign=top> <td class=even><a HREF="http://sourcenav.sourceforge.net/">Source-Navigator</a></td> <td class=even>un strumento GPL per l'analisi del codice sorgente</td> </tr> </table> <br> <h4>Strumenti per creare interfacce utente (GUI)</h4> <table width="100%" border=0 cellspacing=2 cellpadding=2> <tr align=left> <th class=header>Link</th> <th class=header width="100%">Commento</th> </tr> <tr valign=top> <td class=even><a HREF="http: <td class=even>costruttore di interfacce Qt</td> </tr> <tr valign=top> <td class=odd><a HREF="http://qtarch.sourceforge.net/">QT-Architect</a></td> <td class=odd>un architetto versatile per l'insieme di widget Qt</td> </tr> <tr valign=top> <td class=even><a HREF="http://web.inter.nl.net/users/eavdmeer/">EBuilder</a></td> <td class=even>uno strumento veloce, efficiente e semplice da usare per disegnare graficamente widgets per Qt</td> </tr> <tr valign=top> <td class=odd><a HREF="http://glade.gnome.org/">Glade</a></td> <td class=odd>strumento per interfacce utente GTK+</td> </tr> </table> <br> <h4>Altro</h4> <table width="100%" border=0 cellspacing=2 cellpadding=2> <tr align=left> <th class=header>Link</th> <th class=header width="100%">Commento</th> </tr> <tr valign=top> <td class=odd><a HREF="http://members.nextra.at/johsixt//kdbg.html">KDbg</a></td> <td class=odd>un debugger per KDE</td> </tr> <tr valign=top> <td class=even><a HREF="http://cervisia.sourceforge.net/">Cervisia</a></td> <td class=even>un frontend grafico per CVS</td> </tr> <tr valign=top> <td class=odd><a HREF="http: <td class=odd>un frontend grafico per CVS</td> </tr> <tr valign=top> <td class=even><a HREF="http: <td class=even>il Data Display Debugger</td> </tr> <tr valign=top> <td class=odd><a HREF="http://uml.sourceforge.net/">Umbrello</a></td> <td class=odd>Umbrello, Modellatore UML</td> </tr> <tr valign=top> <td class=even><a HREF="http://kprof.sourceforge.net/">KProf</a></td> <td class=even>uno strumento per il profiling visuale per KDE</td> </tr> </table> <?php module_tail(); ?>
package com.skyline.model.core; import java.io.Serializable; import javax.persistence.Embeddable; /** * * @author Gabriel */ @Embeddable public class VotingSystem implements Comparable<Object>, Serializable { private int upVote; private int downVote; public VotingSystem() { this(0, 0); } public VotingSystem(int up, int down) { this.upVote = up; this.downVote = down; } public int getUpVote() { return upVote; } public int getDownVote() { return downVote; } public int getValue() { return upVote - downVote; } public void addUpVote() { upVote += 1; } public void addDownVote() { downVote += 1; } @Override public boolean equals(Object o) { if (o instanceof VotingSystem) { VotingSystem vS = (VotingSystem) o; return this.getValue() == vS.getValue(); } return false; } @Override public String toString() { return "Votes = \n{ upVotes = " + upVote + " \ndownVotes = " + downVote + "\nvalue = " + getValue(); } /** * * @return 1 if self's vote difference is greater, 0 if equals and -1 if lesser */ public int compareTo(Object o) { if (o instanceof VotingSystem) { if (this.equals(o)) { return 0; } VotingSystem vs = (VotingSystem) o; if (this.getValue() > vs.getValue()) { return 1; } } return -1; } }
/** * @file temperature.js * @author Antonino Parisi <tabman83@gmail.com> * @date 28/02/2015 16:41 * @description Temperature data provider */ (function(angular, undefined) { 'use strict'; angular.module('PHMApp').factory('Temperature', ['$resource', 'appSettings', function($resource, appSettings) { var baseUrl = window.location.protocol + '//' + window.location.hostname + ':' + appSettings.api.port; return $resource(baseUrl+'/temperatures'); }]); })(angular);
Packages for Check_MK Homepage of Check_MK: http://mathias-kettner.de/check_mk.html # mk_oracle This plugin was redesigned in cooperation between Mathias Kettner and Thorsten Bruhns. mk_oracle use the new run_cached in this plugin which makes the future development much easier then before. The original plugin needs an agent from 1.2.5i5 onwards. This version is a backport for Check_MK 1.2.2 or newer. It should run on older versions as well but it is only tested on 1.2.5i5. I will stop the backporting for this plugin with the next production version (1.2.6) of Check_MK. ## Requirements * Linux RDBMS 9.2, 10.2, 11.1, 11.2, XE 11.2, 12.1 * AIX 5.3 RDBMS 11.2 * ASM: 10.2, 11.1, 11.2, 12.1 * Check_MK Agent 1.2.2p2 or newer ## How to configure the plugin The configuration is very simple since 2014.09.14_1.2.2p0_tbr. The usage of an Oracle wallet is not documented here. Copy sqlnet.ora to $MK_CONFDIR. This file is needed for the Oracle Client to prevent unwanted diagnostic data to the homedirectory of root. An Oracle wallet also needs the sqlnet.ora. Configure a Database User This depends on the instance_type. # Normal Instance: sqlplus / as sysdba create user check_mk identified by monitoring; grant connect, select_catalog_role to check_mk; # ASM Instance sqlplus / as sysasm create user check_mk identified by monitoring; grant sysdba to check_mk; Normaly the sysdba is not supported for ASM anymore. This is still working under 11.2 and 12.1 and has the advantage that check_mk is not able to stop the Instance but can read the needed data from the Instance. Do not use special characters like '$&" or spaces in passwords. Configure $MK_CONFDIR/mk_oracle.cfg The mk_oracle.cfg has some options. ASMUSER='user:password:sysdba' DBUSER='user:password:sysdba/sysoper:hostname:port' DBUSER_<ORACLE_SID>='user:password:sysdba/sysoper:hostname:port' DBUSER= is used as a default for all normal Database Instances. This can be overwritten by an individual configuration with DBUSER_<ORACLE_SID>. * sysdba/sysoper is empty * hostname localhost * port 1521 ASMUSER='user:password:sysdba' Example: ASMUSER="asmsnmp:asmsnmp:sysdba" DBUSER="check_mk:monitoring" DBUSER_tux="check_mk:monitoring:sysdba" Test the plugin Login as root export MK_CONFDIR=/etc/check_mk /usr/lib/check_mk_agent/plugins/mk_oracle -t ## known issues * some pnp-templates are missing * man-pages are missing ## Version History * 2015.01.19_1.2.2p0_tbr: <API key>: Bugfix for 'params_value' referenced before assignment * 2015.01.19_1.2.2p0_tbr: oracle_undostat: Code cleanup for UNKNOWN state marker * 2015.01.14_1.2.2p0_tbr: mk_oracle: Added missing rules for oracle_jobs and oracle_undostat * 2015.01.12_1.2.2p0_tbr: oracle_rman: Check for new format from agent * 2015.01.12_1.2.2p0_tbr: oracle_rman: new SQL for FULL and INCR Backups * 2015.01.12_1.2.2p0_tbr: oracle_jobs: new SQL for jobs without log information * 2015.01.12_1.2.2p0_tbr: oracle_jobs: added rules for missing job and missing log information * 2015.01.12_1.2.2p0_tbr: #1826 <API key>: New rule for apply_lag_min, removed default rule * 2015.01.12_1.2.2p0_tbr: #1825 <API key>: backupcheck for user managed backups * 2015.01.12_1.2.2p0_tbr: #1822 oracle_undostat: rule for non space error count * 2014.12.29_1.2.2p0_tbr: moved sqlnet.ora to cfg_samples * 2014.12.29_1.2.2p0_tbr: #1821 FIX mk_oracle: changed connection to dedicated server mode * 2014.12.29_1.2.2p0_tbr: #1824 FIX <API key>: removed default values from Check * 2014.12.29_1.2.2p0_tbr: #1821 FIX mk_oracle: changed connection to dedicated server mode * 2014.12.29_1.2.2p0_tbr: #1391 FIX oracle_instance: New function for Primary Database not OPEN * 2014.12.29_1.2.2p0_tbr: #1726 Move variable data of Linux/UNIX agents to /var/lib/check_mk_agent * 2014.12.05_1.2.2p0_tbr: #1390 FIX mk_oracle: better detection of RMAN Archivelog Backups * 2014.11.25_1.2.2p0_tbr: #1511 FIX oracle_jobs: avoid broken checks, make compatible with old version * 2014.11.24_1.2.2p0_tbr: #1388 FIX <API key>: fixed wrong calculation of free space in NORMAL/HIGH redundancy Disk Groups * 2014.11.12_1.2.2p0_tbr: #1824 FIX <API key>: removed default values from Check * 2014.11.04_1.2.2p0_tbr: #1389 FIX oracle_rman: detect failed jobs * 2014.10.28_1.2.2p0_tbr: bugfix for ORACLE_SID with '_' * 2014.10.28_1.2.2p0_tbr: fixed dataguard_stat availible from 10.2 onwards * 2014.10.28_1.2.2p0_tbr: fixed missing executes of sql for 10.1 * 2014.10.28_1.2.2p0_tbr: fixed forever running Jobs in oracle_jobs * 2014.10.28_1.2.2p0_tbr: added new Instance MGMTDB for Oracle 12.1.0.2 * 2014.10.01_1.2.2p0_tbr: Bugfix for Environments with different Oracle Versions * 2014.09.30_1.2.2p0_tbr: Oracle 9.2 is working with limited checks * 2014.09.28_1.2.2p0_tbr: added missing mk_oracle mk_oracle.aix for new ASM check * 2014.09.27_1.2.2p0_tbr: oracle_instance added ORA +ASM Instance check * 2014.09.27_1.2.2p0_tbr: Bugfix for ASM <= 10.2 * 2014.09.27_1.2.2p0_tbr: Replaced sed -r with grep * 2014.09.27_1.2.2p0_tbr: Code Cleanup * 2014.09.23_1.2.2p0_tbr: WATO rule for default increment * 2014.09.23_1.2.2p0_tbr: merged all changes from mk_oracle to mk_oracle.aix * 2014.09.17_1.2.2p0_tbr: fixed broken ASYNC Sections * 2014.09.14_1.2.2p0_tbr: oracle_performance renamed Check from ORA ORACLE_SID Perf-Data to ORA ORACLE_SID Performance. A reinventory is needed! * 2014.09.14_1.2.2p0_tbr: oracle_performance fix for Physical Standby Databases * 2014.09.14_1.2.2p0_tbr: oracle_instance new WATO rule for archivelog, noarchivelog, force logging, no force logging, logins and uptime * 2014.09.14_1.2.2p0_tbr: <API key>: Bugfix for OFFLINE datafiles * 2014.09.14_1.2.2p0_tbr: mk_oracle_dbuser.conf moved to mk_oracle.cfg * 2014.09.14_1.2.2p0_tbr: asm_diskgroup enabled by default * 2014.09.14_1.2.2p0_tbr: automatic detection of Sections for all Database Versions. No need to configure mk_oracle.cfg for that anymore. * 2014.08.29_1.2.2p0_tbr: added missing changes for removing tnsnames.ora requirements * 2014.08.26_1.2.2p0_tbr: New Version numbering due to irritations between Check_MK and this plugin (timestamp of creation the mkp + compatible against Check_MK-Version + _tbr) * 2014.08.26_1.2.2p0_tbr: added owner in oracle_jobs service, added req_mir_free_space and offline disk in <API key> * 2014.08.26_1.2.2p0_tbr: sqlplus.sh is not required anymore, tnsnames.ora is replaced with more fields in mk_oracle_dbusers.conf * 2014.08.26_1.2.2p0_tbr: oracle_performance gets some performance data from Oracle * 2014.08.26_1.2.2p0_tbr: Testmode added: mk_oracle -t * 1.2.3: Bugfix wrong order of values in default parameters in <API key> * 1.2.2: Bugfix sqlplus.sh, wallet is usable again * 1.2.0: New oracle_locks, <API key> Bugfix oracle_job, <API key>. More feautures in sqlplus.sh * 1.1.1: Bugfix oracle_instance & oracle_jobs, some perfometers * 1.1.0: New Recovery State for Standby Databases * 1.0.0: Redesign of whole plugin * 0.7.5: Bugfix UNKNOWN services every 10 minutes from mk_oracle * 0.7.4: Bugfix removed nasty debug print from oracle_instance * 0.7.3: Bugfix in oracle_instance * 0.7.2: Bugfix sqlplus.sh for EZCONNECT * 0.7.1: 1st big release on github # mk_oracle_crs This plugin is used to check an Oracle Grid-Infrastructure or Oracle Restart. ## Requirements * Linux Grid-Infrastructure or Oracle Restart 11.2 + 12.1, Oracle CRS 10.2 + 11.1 * Check_MK Agent 1.2.2p2 or newer ## Version History * 2015.01.16.1.2.2p0_tbr: Plugin compatibility against CRS 10.2 and 11.1 * 2014.11.06.1.2.2p0_tbr: fix for Pending Services in CRS or GI Environments * 2014.09.28_1.2.2p0_tbr: Support for Gird-Infrastructure 12.1 added * 2014.09.28_1.2.2p0_tbr: Support for Gird-Infrastructure 12.1 added * 2014.08.29_1.2.2p0_tbr: ae03fa3 Fixed shell expansion and lower problem in mk_oracle_crs * 0.1.0: 1st release on github ## Local Checks # plugin_cksum Calculates a checksum with cksum over all plugins which are found in $MK_LIBDIR/plugins. The state is OK when plugins are found and UNKNOWN when the directory or cksum is missing. Thorsten Bruhns
<?php include_once('../../config/symbini.php'); include_once($SERVER_ROOT.'/classes/KeyEditorManager.php'); header("Cache-control: private; Content-Type: text/html; charset=".$CHARSET); if(!$SYMB_UID) header('Location: ../../profile/index.php?refurl=../ident/tools/editor.php?'.htmlspecialchars($_SERVER['QUERY_STRING'], ENT_QUOTES)); $action = array_key_exists("action",$_POST)?$_POST["action"]:""; $langValue = array_key_exists("lang",$_REQUEST)?$_REQUEST["lang"]:$DEFAULT_LANG; $charValue = array_key_exists("char",$_REQUEST)?$_REQUEST["char"]:""; $childrenStr = array_key_exists("children",$_REQUEST)?$_REQUEST["children"]:""; $tid = array_key_exists("tid",$_REQUEST)?$_REQUEST["tid"]:""; $editorManager = new KeyEditorManager(); if(!$tid && $childrenStr){ $childrenArr = explode(',',$childrenStr); $tid = array_pop($childrenArr); $childrenStr = implode(',',$childrenArr); } $editorManager->setLanguage($langValue); $editorManager->setTid($tid); $isEditor = false; if($IS_ADMIN || array_key_exists("KeyEditor",$USER_RIGHTS) || array_key_exists("KeyAdmin",$USER_RIGHTS)){ $isEditor = true; } if($isEditor && $action){ if($action=="Submit Changes"){ $addArr = array_key_exists('add',$_POST)?$_POST['add']:null; $removeArr = array_key_exists('remove',$_POST)?$_POST['remove']:null; $editorManager->processTaxa($addArr,$removeArr); } } ?> <html> <head> <title><?php echo $DEFAULT_TITLE; ?> Identification Character Editor</title> <?php $activateJQuery = false; if(file_exists($SERVER_ROOT.'/includes/head.php')){ include_once($SERVER_ROOT.'/includes/head.php'); } else{ echo '<link href="'.$CLIENT_ROOT.'/css/jquery-ui.css" type="text/css" rel="stylesheet" />'; echo '<link href="'.$CLIENT_ROOT.'/css/base.css?ver=1" type="text/css" rel="stylesheet" />'; echo '<link href="'.$CLIENT_ROOT.'/css/main.css?ver=1" type="text/css" rel="stylesheet" />'; } ?> <script type="text/javascript" src="<?php echo $CLIENT_ROOT; ?>/js/jquery.js"></script> <script type="text/javascript" src="<?php echo $CLIENT_ROOT; ?>/js/jquery-ui.js"></script> <script type="text/javascript"> var dataChanged = false; var headingDivOpen = true; window.onbeforeunload = verifyClose; function verifyClose() { if (dataChanged == true) { return "You will lose any unsaved data if you don't first submit your changes!"; } } function toggle(target){ $("#"+target).toggle(); $("#plus-"+target).toggle(); $("#minus-"+target).toggle(); } function toggleAll(){ if(headingDivOpen){ $(".headingDiv").hide(); headingDivOpen = false; } else{ $(".headingDiv").show(); headingDivOpen = true; } } function showSearch(){ document.getElementById("searchDiv").style.display="block"; document.getElementById("searchDisplay").style.display="none"; } function openPopup(urlStr,windowName){ var wWidth = 900; if(document.body.offsetWidth) wWidth = document.body.offsetWidth*0.9; if(wWidth > 1200) wWidth = 1200; newWindow = window.open(urlStr,windowName,'scrollbars=1,toolbar=0,resizable=1,width='+(wWidth)+',height=500,left=50,top=150'); if (newWindow.opener == null) newWindow.opener = self; } </script> </head> <body> <div id="innertext"> <?php if($isEditor && $tid){ ?> <form action="editor.php" method="post" onsubmit="dataChanged=false;"> <?php $sn = $editorManager->getTaxonName(); if($editorManager->getRankId() > 140) $sn = "<i>$sn</i>"; echo "<div style='float:right;'>"; if($editorManager->getRankId() > 140){ echo "<a href='editor.php?tid=".$editorManager->getParentTid()."&children=".($childrenStr?$childrenStr.',':'').$tid."'>edit parent</a>&nbsp;&nbsp;"; } if($childrenStr){ echo "<br><a href='editor.php?children=".$childrenStr."'>back to child</a>"; } echo '</div>'; echo '<h2>'.$sn.'</h2>'; $cList = $editorManager->getCharList(); $depArr = $editorManager->getCharDepArray(); $charStatesList = $editorManager->getCharStates(); if($cList){ echo '<div><a href="#" onclick="toggleAll();return false;">open/close all</a></div>'; $count = 0; foreach($cList as $heading => $charArray){ $headingID = str_replace(array(' ','&'),'_',$heading); if(!$charValue){ echo '<fieldset>'; echo '<legend style="font-weight:bold;font-size:120%;color:#990000;">'; echo '<span id="minus-'.$headingID.'" onclick="toggle(\''.$headingID.'\')" style="display:none;"><img src="../../images/minus_sm.png"></span> '; echo '<span id="plus-'.$headingID.'" onclick="toggle(\''.$headingID.'\')"><img src="../../images/plus_sm.png"></span> '; echo $heading.'</legend>'; } echo '<div class="headingDiv" id="'.$headingID.'" style="text-indent:1em;">'; foreach($charArray as $cidKey => $charNameStr){ if(isset($charStatesList[$cidKey]) && (!$charValue || $charValue == $cidKey)){ echo "<div id='chardiv".$cidKey."' style='display:".(array_key_exists($cidKey,$depArr)?"hidden":"block").";'>"; echo "<div style='margin-top:1em;'><span style='font-weight:bold;'>$charNameStr</span>\n"; if($editorManager->getRankId() > 140){ echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style='font-size:smaller;'>"; echo "<a href=\"#\" onclick=\"openPopup('editor.php?tid=".$editorManager->getParentTid()."&char=".$cidKey."','technical');\">parent</a>"; echo "</span>\n"; } echo "</div>\n"; echo "<div style='font-size:smaller; text-indent:2.5em;'>Add&nbsp;&nbsp;Remove</div>\n"; $cStates = $charStatesList[$cidKey]; foreach($cStates as $csKey => $csValue){ $testStr = $cidKey."_".$csKey; $charPresent = $editorManager->isSelected($testStr); $inh = $editorManager->getInheritedStr($testStr); $displayStr = ($charPresent?"<span style='font-weight:bold;'>":"").$csValue.$inh.($charPresent?"</span>":""); echo "<div style='text-indent:2em;'><input type='checkbox' name='add[]' ".($charPresent && !$inh?"disabled='true' ":" ")." value='".$testStr."' onChange='dataChanged=true;'/>"; echo "&nbsp;&nbsp;&nbsp;<input type='checkbox' name='remove[]' ".(!$charPresent || $inh?"disabled='true' ":" ")."value='".$testStr."' onChange='dataChanged=true;'/>"; echo "&nbsp;&nbsp;&nbsp;$displayStr</div>\n"; } echo '</div>'; $count++; if($count%3 == 0) echo "<div style='margin-top:1em;'><input type='submit' name='action' value='Submit Changes'/></div>\n"; } } if(!$charValue) echo '</fieldset>'; } echo '<div style="margin-top:1em;"><input type="submit" name="action" value="Submit Changes"/></div>'; //Hidden values to maintain values and display mode if($charValue){ echo "<div><br><b>Note:</b> changes made here will not be reflected on child page until page is refreshed.</div>"; echo "<div><input type='hidden' name='char' value='".$charValue."'/></div>"; } ?> <div> <input type="hidden" name="tid" value="<?php echo $editorManager->getTid(); ?>" /> <input type="hidden" name="children" value="<?php echo $childrenStr; ?>" /> <input type="hidden" name="lang" value="<?php echo $langValue; ?>" /> </div> <?php } ?> </form> <?php } else{ echo "<h1>You do not have authority to edit character data or there is a problem with the database connection.</h1>"; } ?> </div> </body> </html>
* { margin: 0; padding: 0; } body { font: 16px Georgia, serif; } #page-wrap { margin: 2% auto; color: white; } #page-wrap > .main { border: 1px solid #999; padding: 1%; margin-bottom: 1px; color: black;} section > div { padding: 20px; } header, nav, section { background: #eee; text-align: center;} footer { background: #eee; text-align: center;} nav span { margin: 0px 10px 0px 0px; width: 100%; display: inline-block;} #ErrorMsgs {color: #f61;font-size:smaler}
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.4"/> <title>tbb::improper_lock Class Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <!-- end header part --> <!-- Generated by Doxygen 1.8.4 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="a00276.html">tbb</a></li><li class="navelem"><a class="el" href="a00083.html">improper_lock</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> &#124; <a href="a00354.html">List of all members</a> </div> <div class="headertitle"> <div class="title">tbb::improper_lock Class Reference</div> </div> </div><!--header <div class="contents"> <p>Exception for PPL locks. <a href="a00083.html#details">More...</a></p> <p><code>#include &lt;tbb_exception.h&gt;</code></p> <div class="dynheader"> Inheritance diagram for tbb::improper_lock:</div> <div class="dyncontent"> <div class="center"> <img src="a00083.png" usemap="#tbb::improper_lock_map" alt=""/> <map id="tbb::improper_lock_map" name="tbb::improper_lock_map"> </map> </div></div> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a> const char *&#160;</td><td class="memItemRight" valign="bottom"><b>what</b> () const throw ()</td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><p>Exception for PPL locks. </p> </div><hr/>The documentation for this class was generated from the following file:<ul> <li>tbb_exception.h</li> </ul> </div><!-- contents --> <hr> <p></p> Copyright &copy; 2005-2016 Intel Corporation. All Rights Reserved. <p></p> Intel, Pentium, Intel Xeon, Itanium, Intel XScale and VTune are registered trademarks or trademarks of Intel Corporation or its subsidiaries in the United States and other countries. <p></p> * Other names and brands may be claimed as the property of others.
<?php namespace Eventum\CustomField; use Doctrine\Common\Collections\ArrayCollection; use Eventum\CustomField\Fields\<API key>; use Eventum\CustomField\Fields\<API key>; use Eventum\CustomField\Fields\<API key>; use Eventum\Model\Entity\CustomField; use Eventum\Model\Entity\IssueCustomField; use Generator; class Converter { public function convertCustomFields(array $customFields, ?int $issueId, ?string $formType): array { $fields = []; foreach ($customFields as $customField) { $fields[] = $this->convertCustomField($customField); } $this->applyBackendValues($fields, $issueId, $formType, false); return $fields; } /** * Convert values to legacy array structures */ public function <API key>(array $customFields, int $issueId, ?string $formType): array { $fields = []; foreach ($this-><API key>($customFields, $issueId) as $row) { $fld_id = $row['fld_id']; /** @var CustomField $cf */ $cf = $row['_cf']; /** @var IssueCustomField $icf */ $icf = $row['_icf']; if ($row['fld_type'] === 'combo') { $row['selected_cfo_id'] = $row['value']; $row['original_value'] = $row['value']; $row['value'] = $icf->getOptionValue(); $row['field_options'] = $this->getOptions($row, $formType, $issueId); // add the select option to the list of values if it isn't on the list (useful for fields with active and non-active items) if (!empty($row['original_value']) && !isset($row['field_options'][$row['original_value']])) { $row['field_options'][$row['original_value']] = $icf->getOptionValue(); } $fields[] = $row; } elseif ($cf->isOptionType()) { // check whether this field is already in the array $found_index = null; foreach ($fields as $y => $field) { if ($field['fld_id'] === $fld_id) { $found_index = $y; } } $original_value = $row['value']; if ($found_index === null) { $row['selected_cfo_id'] = [$row['value']]; $row['value'] = $icf->getOptionValue(); $row['field_options'] = $this->getOptions($row, $formType, $issueId); $fields[] = $row; $found_index = count($fields) - 1; } else { $fields[$found_index]['value'] .= ', ' . $icf->getOptionValue(); $fields[$found_index]['selected_cfo_id'][] = $row['value']; } // add the select option to the list of values if it isn't on the list (useful for fields with active and non-active items) if ($original_value !== null && !in_array($original_value, $fields[$found_index]['field_options'], true)) { $fields[$found_index]['field_options'][$original_value] = $icf->getOptionValue(); } } else { $fields[] = $row; } } $this->applyBackendValues($fields, $issueId, $formType); return $fields; } private function applyBackendValues(array &$fields, ?int $issueId, ?string $formType, bool $skipValueOptions = true): void { foreach ($fields as &$field) { $fld_id = $field['fld_id']; /** @var CustomField $cf */ $cf = $field['_cf']; $backend = $cf->getProxy(); if ($backend && $backend->hasInterface(<API key>::class)) { $field['<API key>'] = $backend->isRequired($fld_id, 'report', $issueId); $field['<API key>'] = $backend->isRequired($fld_id, 'anonymous', $issueId); $field['<API key>'] = $backend->isRequired($fld_id, 'close', $issueId); $field['<API key>'] = $backend->isRequired($fld_id, 'edit', $issueId); } if ($backend && $backend->hasInterface(<API key>::class)) { $field['validation_js'] = $backend->getValidationJs($fld_id, $formType, $issueId); } else { $field['validation_js'] = ''; } if (!$skipValueOptions) { $field['field_options'] = $this->getOptions($field, $formType); if ($backend && $backend->hasInterface(<API key>::class)) { $field['default_value'] = $backend->getDefaultValue($fld_id); } else { $field['default_value'] = ''; } } // do not expose these outside. yet unset($field['_cf'], $field['_icf']); } } private function getOptions(array $field, ?string $formType = null, ?int $issueId = null): array { /** @var CustomField $cf */ $cf = $field['_cf']; return $cf->getOptionValues($formType, $issueId); } private function <API key>(array $customFields, int $issueId): Generator { $result = new ArrayCollection(); /** @var CustomField $cf */ foreach ($customFields as $cf) { $issueFields = $cf-><API key>($issueId); if ($issueFields->count()) { foreach ($issueFields as $isc) { $row = $this-><API key>($isc); $result->add($row); } } else { // create empty IssueCustomField for left-joined issues $icf = new IssueCustomField(); $icf->customField = $cf; $row = $this-><API key>($icf); $result->add($row); } } yield from $result; } private function <API key>(IssueCustomField $icf): array { $result = $this->convertCustomField($icf->customField); $value = $icf->getValue(); $result += [ '_icf' => $icf, 'value' => $value, 'icf_value' => $icf->getStringValue(), 'icf_value_date' => $icf->getDate(), 'icf_value_integer' => $icf->getIntegerValue(), ]; return $result; } private function convertCustomField(CustomField $field): array { $result = $field->toArray(); $result['_cf'] = $field; return $result; } }
{% extends '_modal.html' %} {% load i18n %} {% block modal_id %}user_import_modal{% endblock %} {% block modal_title%}{% trans "Import user" %}{% endblock %} {% block modal_body %} <p class="text-success">{% trans "Download template or use export excel format" %}</p> <form method="post" action="{% url 'users:user-import' %}" id="fm_user_import" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label class="control-label" for="id_users">{% trans "Template" %}</label> <a href="{% url 'users:user-export' %}" style="display: block">{% trans 'Download' %}</a> </div> <div class="form-group"> <label class="control-label" for="id_users">{% trans "Users excel file" %}</label> <input id="id_users" type="file" name="file" /> <span class="help-block">{% trans 'If set id, will use this id update existed' %}</span> </div> </form> <p> <p class="text-success" id="id_created"></p> <p id="id_created_detail"></p> <p class="text-warning" id="id_updated"></p> <p id="id_updated_detail"></p> <p class="text-danger" id="id_failed"></p> <p id="id_failed_detail"></p> </p> {% endblock %} {% block modal_confirm_id %}btn_user_import{% endblock %}
<?php / // This funstion validates a plain text password with an // encrpyted password function <API key>($plain, $encrypted) { if (tep_not_null($plain) && tep_not_null($encrypted)) { // split apart the hash / salt $stack = explode(':', $encrypted); if (sizeof($stack) != 2) return false; if (md5($stack[1] . $plain) == $stack[0]) { return true; } } return false; } / // This function makes a new password from a plaintext password. function <API key>($plain) { $password = ''; for ($i=0; $i<10; $i++) { $password .= tep_rand(); } $salt = substr(md5($password), 0, 2); $password = md5($salt . $plain) . ':' . $salt; return $password; } ?>
FactoryBot.define do factory :column, class: GtfsReader::Config::Column do sequence(:name) { |n| "column_ opts { {} } initialize_with { new name, opts } end end
#include <linux/bug.h> #include <linux/delay.h> #include <linux/err.h> #include <linux/gpio.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/regmap.h> #include <linux/regulator/of_regulator.h> #include <linux/platform_device.h> #include <linux/regulator/driver.h> #include <linux/regulator/machine.h> #include <linux/mfd/samsung/core.h> #include <linux/mfd/samsung/s2mps11.h> struct s2mps11_info { struct regulator_dev *rdev[<API key>]; unsigned int opmode[<API key>]; }; /* Some LDOs supports [LPM/Normal]ON mode during suspend state */ static int s2m_set_mode(struct regulator_dev *rdev, unsigned int mode) { struct s2mps11_info *s2mps11 = rdev_get_drvdata(rdev); unsigned int val; int ret, id = rdev_get_id(rdev); switch (mode) { case SEC_OPMODE_OFF: /* ON in Standby Mode */ val = 0x0 << <API key>; break; case SEC_OPMODE_SUSPEND: /* ON in Standby Mode */ val = 0x1 << <API key>; break; case SEC_OPMODE_ON: /* ON in Normal Mode */ val = 0x3 << <API key>; break; default: pr_warn("%s: <API key> : 0x%x not supported\n", rdev->desc->name, mode); return -EINVAL; } ret = regmap_update_bits(rdev->regmap, rdev->desc->enable_reg, rdev->desc->enable_mask, val); if (ret) return ret; s2mps11->opmode[id] = val; return 0; } static int s2m_enable(struct regulator_dev *rdev) { struct s2mps11_info *s2mps11 = rdev_get_drvdata(rdev); return regmap_update_bits(rdev->regmap, rdev->desc->enable_reg, rdev->desc->enable_mask, s2mps11->opmode[rdev_get_id(rdev)]); } static int get_ramp_delay(int ramp_delay) { unsigned char cnt = 0; ramp_delay /= 6; while (true) { ramp_delay = ramp_delay >> 1; if (ramp_delay == 0) break; cnt++; } return cnt; } static int s2m_set_ramp_delay(struct regulator_dev *rdev, int ramp_delay) { int ramp_reg, ramp_shift, reg_id = rdev_get_id(rdev); int ramp_mask = 0x03; unsigned int ramp_value = 0; ramp_value = get_ramp_delay(ramp_delay / 1000); if (ramp_value > 4) { pr_warn("%s: ramp_delay: %d not supported\n", rdev->desc->name, ramp_delay); } switch (reg_id) { case S2MPS11_BUCK1: case S2MPS11_BUCK6: ramp_reg = <API key>; ramp_shift = 4; break; case S2MPS11_BUCK2: ramp_reg = S2MPS11_REG_RAMP; ramp_shift = 6; break; case S2MPS11_BUCK3: case S2MPS11_BUCK4: ramp_reg = S2MPS11_REG_RAMP; ramp_shift = 4; break; case S2MPS11_BUCK7: case S2MPS11_BUCK8: case S2MPS11_BUCK10: ramp_reg = <API key>; ramp_shift = 2; break; case S2MPS11_BUCK9: ramp_reg = <API key>; ramp_shift = 0; break; case S2MPS11_BUCK5: ramp_reg = <API key>; ramp_shift = 6; break; default: return -EINVAL; } return regmap_update_bits(rdev->regmap, ramp_reg, ramp_mask << ramp_shift, ramp_value << ramp_shift); } static int <API key>(struct regulator_dev *rdev, unsigned int old_selector, unsigned int new_selector) { unsigned int ramp_delay = 0; int old_volt, new_volt; if (rdev->constraints->ramp_delay) ramp_delay = rdev->constraints->ramp_delay; else if (rdev->desc->ramp_delay) ramp_delay = rdev->desc->ramp_delay; if (ramp_delay == 0) { pr_warn("%s: ramp_delay not set\n", rdev->desc->name); return -EINVAL; } /* sanity check */ if (!rdev->desc->ops->list_voltage) return -EINVAL; old_volt = rdev->desc->ops->list_voltage(rdev, old_selector); new_volt = rdev->desc->ops->list_voltage(rdev, new_selector); if (old_selector < new_selector) return DIV_ROUND_UP(new_volt - old_volt, ramp_delay); return 0; } static struct regulator_ops s2mps11_ldo_ops = { .list_voltage = <API key>, .map_voltage = <API key>, .is_enabled = <API key>, .enable = s2m_enable, .disable = <API key>, .get_voltage_sel = <API key>, .set_voltage_sel = <API key>, .<API key> = <API key>, .set_mode = s2m_set_mode, }; static struct regulator_ops s2mps11_buck_ops = { .list_voltage = <API key>, .map_voltage = <API key>, .is_enabled = <API key>, .enable = s2m_enable, .disable = <API key>, .get_voltage_sel = <API key>, .set_voltage_sel = <API key>, .<API key> = <API key>, .set_mode = s2m_set_mode, .set_ramp_delay = s2m_set_ramp_delay, }; #define _BUCK(macro) S2MPS11_BUCK##macro #define _buck_ops(num) s2mps11_buck_ops##num #define _LDO(macro) S2MPS11_LDO##macro #define _REG(ctrl) S2MPS11_REG##ctrl #define _ldo_ops(num) s2mps11_ldo_ops##num #define BUCK_DESC(_name, _id, _ops, m, s, v, e) { \ .name = _name, \ .id = _id, \ .ops = _ops, \ .type = REGULATOR_VOLTAGE, \ .owner = THIS_MODULE, \ .min_uV = m, \ .uV_step = s, \ .n_voltages = <API key>, \ .vsel_reg = v, \ .vsel_mask = <API key>, \ .enable_reg = e, \ .enable_mask = S2MPS11_ENABLE_MASK \ } #define LDO_DESC(_name, _id, _ops, m, s, v, e) { \ .name = _name, \ .id = _id, \ .ops = _ops, \ .type = REGULATOR_VOLTAGE, \ .owner = THIS_MODULE, \ .min_uV = m, \ .uV_step = s, \ .n_voltages = <API key>, \ .vsel_reg = v, \ .vsel_mask = <API key>, \ .enable_reg = e, \ .enable_mask = S2MPS11_ENABLE_MASK \ } enum regulator_desc_type { S2MPS11_DESC_TYPE0 = 0, }; static struct regulator_desc regulators[][<API key>] = { [S2MPS11_DESC_TYPE0] = { /* name, id, ops, min_uv, uV_step, vsel_reg, enable_reg */ LDO_DESC("LDO1", _LDO(1), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP2), _REG(_L1CTRL), _REG(_L1CTRL)), LDO_DESC("LDO2", _LDO(2), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L2CTRL), _REG(_L2CTRL)), LDO_DESC("LDO3", _LDO(3), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L3CTRL), _REG(_L3CTRL)), LDO_DESC("LDO4", _LDO(4), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L4CTRL), _REG(_L4CTRL)), LDO_DESC("LDO5", _LDO(5), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L5CTRL), _REG(_L5CTRL)), LDO_DESC("LDO6", _LDO(6), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP2), _REG(_L6CTRL), _REG(_L6CTRL)), LDO_DESC("LDO7", _LDO(7), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L7CTRL), _REG(_L7CTRL)), LDO_DESC("LDO8", _LDO(8), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L8CTRL), _REG(_L8CTRL)), LDO_DESC("LDO9", _LDO(9), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L9CTRL), _REG(_L9CTRL)), LDO_DESC("LDO10", _LDO(10), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L10CTRL), _REG(_L10CTRL)), LDO_DESC("LDO11", _LDO(11), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP2), _REG(_L11CTRL), _REG(_L11CTRL)), LDO_DESC("LDO12", _LDO(12), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L12CTRL), _REG(_L12CTRL)), LDO_DESC("LDO13", _LDO(13), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L13CTRL), _REG(_L13CTRL)), LDO_DESC("LDO14", _LDO(14), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L14CTRL), _REG(_L14CTRL)), LDO_DESC("LDO15", _LDO(15), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L15CTRL), _REG(_L15CTRL)), LDO_DESC("LDO16", _LDO(16), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L16CTRL), _REG(_L16CTRL)), LDO_DESC("LDO17", _LDO(17), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L17CTRL), _REG(_L17CTRL)), LDO_DESC("LDO18", _LDO(18), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L18CTRL), _REG(_L18CTRL)), LDO_DESC("LDO19", _LDO(19), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L19CTRL), _REG(_L19CTRL)), LDO_DESC("LDO20", _LDO(20), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L20CTRL), _REG(_L20CTRL)), LDO_DESC("LDO21", _LDO(21), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L21CTRL), _REG(_L21CTRL)), LDO_DESC("LDO22", _LDO(22), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP2), _REG(_L22CTRL), _REG(_L22CTRL)), LDO_DESC("LDO23", _LDO(23), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP2), _REG(_L23CTRL), _REG(_L23CTRL)), LDO_DESC("LDO24", _LDO(24), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L24CTRL), _REG(_L24CTRL)), LDO_DESC("LDO25", _LDO(25), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L25CTRL), _REG(_L25CTRL)), LDO_DESC("LDO26", _LDO(26), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L26CTRL), _REG(_L26CTRL)), LDO_DESC("LDO27", _LDO(27), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP2), _REG(_L27CTRL), _REG(_L27CTRL)), LDO_DESC("LDO28", _LDO(28), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L28CTRL), _REG(_L28CTRL)), LDO_DESC("LDO29", _LDO(29), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L29CTRL), _REG(_L29CTRL)), LDO_DESC("LDO30", _LDO(30), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L30CTRL), _REG(_L30CTRL)), LDO_DESC("LDO31", _LDO(31), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L31CTRL), _REG(_L31CTRL)), LDO_DESC("LDO32", _LDO(32), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L32CTRL), _REG(_L32CTRL)), LDO_DESC("LDO33", _LDO(33), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L33CTRL), _REG(_L33CTRL)), LDO_DESC("LDO34", _LDO(34), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L34CTRL), _REG(_L34CTRL)), LDO_DESC("LDO35", _LDO(35), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP2), _REG(_L35CTRL), _REG(_L35CTRL)), LDO_DESC("LDO36", _LDO(36), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L36CTRL), _REG(_L36CTRL)), LDO_DESC("LDO37", _LDO(37), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L37CTRL), _REG(_L37CTRL)), LDO_DESC("LDO38", _LDO(38), &_ldo_ops(), _LDO(_MIN1), _LDO(_STEP1), _REG(_L38CTRL), _REG(_L38CTRL)), BUCK_DESC("BUCK1", _BUCK(1), &_buck_ops(), _BUCK(_MIN1), _BUCK(_STEP1), _REG(_B1CTRL2), _REG(_B1CTRL1)), BUCK_DESC("BUCK2", _BUCK(2), &_buck_ops(), _BUCK(_MIN1), _BUCK(_STEP1), _REG(_B2CTRL2), _REG(_B2CTRL1)), BUCK_DESC("BUCK3", _BUCK(3), &_buck_ops(), _BUCK(_MIN1), _BUCK(_STEP1), _REG(_B3CTRL2), _REG(_B3CTRL1)), BUCK_DESC("BUCK4", _BUCK(4), &_buck_ops(), _BUCK(_MIN1), _BUCK(_STEP1), _REG(_B4CTRL2), _REG(_B4CTRL1)), BUCK_DESC("BUCK5", _BUCK(5), &_buck_ops(), _BUCK(_MIN1), _BUCK(_STEP1), _REG(_B5CTRL2), _REG(_B5CTRL1)), BUCK_DESC("BUCK6", _BUCK(6), &_buck_ops(), _BUCK(_MIN1), _BUCK(_STEP1), _REG(_B6CTRL2), _REG(_B6CTRL1)), BUCK_DESC("BUCK9", _BUCK(9), &_buck_ops(), _BUCK(_MIN3), _BUCK(_STEP3), _REG(_B9CTRL2), _REG(_B9CTRL1)), BUCK_DESC("BUCK10", _BUCK(10), &_buck_ops(), _BUCK(_MIN2), _BUCK(_STEP2), _REG(_B10CTRL2), _REG(_B10CTRL1)), }, }; #ifdef CONFIG_OF static int <API key>(struct sec_pmic_dev *iodev, struct sec_platform_data *pdata) { struct device_node *pmic_np, *regulators_np, *reg_np; struct sec_regulator_data *rdata; unsigned int i; pmic_np = iodev->dev->of_node; if (!pmic_np) { dev_err(iodev->dev, "could not find pmic sub-node\n"); return -ENODEV; } regulators_np = <API key>(pmic_np, "regulators"); if (!regulators_np) { dev_err(iodev->dev, "could not find regulators sub-node\n"); return -EINVAL; } /* count the number of regulators to be supported in pmic */ pdata->num_regulators = 0; <API key>(regulators_np, reg_np) { pdata->num_regulators++; } rdata = devm_kzalloc(iodev->dev, sizeof(*rdata) * pdata->num_regulators, GFP_KERNEL); if (!rdata) { dev_err(iodev->dev, "could not allocate memory for regulator data\n"); return -ENOMEM; } pdata->regulators = rdata; <API key>(regulators_np, reg_np) { for (i = 0; i < ARRAY_SIZE(regulators[S2MPS11_DESC_TYPE0]); i++) if (!of_node_cmp(reg_np->name, regulators[S2MPS11_DESC_TYPE0][i].name)) break; if (i == ARRAY_SIZE(regulators[S2MPS11_DESC_TYPE0])) { dev_warn(iodev->dev, "don't know how to configure regulator %s\n", reg_np->name); continue; } rdata->id = i; rdata->initdata = <API key>( iodev->dev, reg_np); rdata->reg_node = reg_np; rdata++; } return 0; } #else static int <API key>(struct sec_pmic_dev *iodev, struct sec_platform_data *pdata) { return 0; } #endif /* CONFIG_OF */ static int s2mps11_pmic_probe(struct platform_device *pdev) { struct sec_pmic_dev *iodev = dev_get_drvdata(pdev->dev.parent); struct sec_platform_data *pdata = iodev->pdata; struct regulator_config config = { }; struct s2mps11_info *s2mps11; int i, ret; ret = sec_reg_read(iodev, S2MPS11_REG_ID, &iodev->rev_num); if (ret < 0) return ret; if (iodev->dev->of_node) { ret = <API key>(iodev, pdata); if (ret) return ret; } if (!pdata) { dev_err(pdev->dev.parent, "Platform data not supplied\n"); return -ENODEV; } s2mps11 = devm_kzalloc(&pdev->dev, sizeof(struct s2mps11_info), GFP_KERNEL); if (!s2mps11) return -ENOMEM; <API key>(pdev, s2mps11); for (i = 0; i < pdata->num_regulators; i++) { int id = pdata->regulators[i].id; config.dev = &pdev->dev; config.regmap = iodev->regmap; config.init_data = pdata->regulators[i].initdata; config.driver_data = s2mps11; config.of_node = pdata->regulators[i].reg_node; s2mps11->opmode[id] = regulators[S2MPS11_DESC_TYPE0][id].enable_mask; s2mps11->rdev[i] = regulator_register( &regulators[S2MPS11_DESC_TYPE0][id], &config); if (IS_ERR(s2mps11->rdev[i])) { ret = PTR_ERR(s2mps11->rdev[i]); dev_err(&pdev->dev, "regulator init failed for %d\n", i); s2mps11->rdev[i] = NULL; goto err; } } return 0; err: for (i = 0; i < <API key>; i++) <API key>(s2mps11->rdev[i]); return ret; } static int s2mps11_pmic_remove(struct platform_device *pdev) { struct s2mps11_info *s2mps11 = <API key>(pdev); int i; for (i = 0; i < <API key>; i++) <API key>(s2mps11->rdev[i]); return 0; } #if defined(<API key>) static void <API key>(struct platform_device *pdev) { struct sec_pmic_dev *iodev = dev_get_drvdata(pdev->dev.parent); unsigned int reg_ctrl1 = 0, retry = 0; for(retry = 0; retry < 5; retry++) { /* PWR_HOLD bit-clear when power off */ if(sec_reg_update(iodev, S2MPS11_REG_CTRL1, 0x00, 0xff)) { printk(KERN_EMERG "%s : S2MPS11 REG CTRL1 Update error! retry %d", __func__, retry); continue; } if(sec_reg_read(iodev, S2MPS11_REG_CTRL1, &reg_ctrl1)) { printk(KERN_EMERG "%s : S2MPS11 REG CTRL1 read error! retry %d", __func__, retry); continue; } // PWR_HOLD not clear. if(reg_ctrl1 & 0x10) { printk(KERN_EMERG "%s : S2MPS11 REG CTRL1 value error!, value = 0x%08X, retry %d", __func__, reg_ctrl1, retry); continue; } else { printk(KERN_EMERG "%s : PWR_HOLD Clear Bit. (retry %d)\n", __func__, retry); break; } } // MMC Power Control for MMC UHS Mode if(sec_reg_read(iodev, S2MPS11_REG_L19CTRL, &reg_ctrl1)) printk(KERN_EMERG "%s : S2MPS11 LDO CTRL19 Error!!\n", __func__); // VDDQ_MMC2 OFF if(sec_reg_update(iodev, S2MPS11_REG_L13CTRL, 0x00, 0x3F)) printk(KERN_EMERG "%s : S2MPS11 LDO CTRL13 Error!!\n", __func__); // VDD_SD_2V8 OFF if(sec_reg_update(iodev, S2MPS11_REG_L19CTRL, 0x00, 0x3F)) printk(KERN_EMERG "%s : S2MPS11 LDO CTRL19 Error!!\n", __func__); mdelay(10); if(sec_reg_update(iodev, S2MPS11_REG_L19CTRL, reg_ctrl1, 0x3F)) printk(KERN_EMERG "%s : S2MPS11 LDO CTRL19 Error!!\n", __func__); if(sec_reg_update(iodev, S2MPS11_REG_L13CTRL, 0xE8, 0xFF)) printk(KERN_EMERG "%s : S2MPS11 LDO CTRL13 Error!!\n", __func__); } #endif static const struct platform_device_id s2mps11_pmic_id[] = { { "s2mps11-pmic", 0}, { }, }; MODULE_DEVICE_TABLE(platform, s2mps11_pmic_id); static struct platform_driver s2mps11_pmic_driver = { .driver = { .name = "s2mps11-pmic", .owner = THIS_MODULE, }, .probe = s2mps11_pmic_probe, .remove = s2mps11_pmic_remove, #if defined(<API key>) .shutdown = <API key>, #endif .id_table = s2mps11_pmic_id, }; static int __init s2mps11_pmic_init(void) { return <API key>(&s2mps11_pmic_driver); } subsys_initcall(s2mps11_pmic_init); static void __exit s2mps11_pmic_exit(void) { <API key>(&s2mps11_pmic_driver); } module_exit(s2mps11_pmic_exit); /* Module information */ MODULE_AUTHOR("Sangbeom Kim <sbkim73@samsung.com>"); MODULE_DESCRIPTION("SAMSUNG S2MPS11 Regulator Driver"); MODULE_LICENSE("GPL");
include $(TOPDIR)/rules.mk PKG_NAME:=sqlite2 PKG_VERSION:=2.8.17 PKG_RELEASE:=2 PKG_SOURCE:=sqlite-$(PKG_VERSION).tar.gz PKG_SOURCE_URL:=http: PKG_MD5SUM:=<API key> PKG_BUILD_DIR:=$(BUILD_DIR)/sqlite-$(PKG_VERSION) PKG_BUILD_DEPENDS:=libncurses libreadline PKG_FIXUP:=libtool PKG_INSTALL:=1 include $(INCLUDE_DIR)/package.mk TARGET_CFLAGS += $(FPIC) define Package/sqlite2/Default SUBMENU:=database TITLE:=SQLite (v2.x) database engine URL:=http: endef define Package/libsqlite2 $(call Package/sqlite2/Default) SECTION:=libs CATEGORY:=Libraries TITLE+= (library) endef define Package/libsqlite2/description SQLite is a small C library that implements a self-contained, embeddable, zero-configuration SQL database engine. This package contains the SQLite (v2.x) shared library, used by other programs. endef define Package/sqlite2-cli $(call Package/sqlite2/Default) SECTION:=utils CATEGORY:=Utilities DEPENDS:=+libsqlite2 +libncurses +libreadline TITLE+= (cli) SUBMENU:=database endef define Package/sqlite2-cli/description SQLite is a small C library that implements a self-contained, embeddable, zero-configuration SQL database engine. This package contains a terminal-based front-end to the SQLite (v2.x) library that can evaluate queries interactively and display the results in multiple formats. endef define Build/Configure $(call Build/Configure/Default, \ --enable-shared \ --enable-static \ , \ config_BUILD_CC="$(HOSTCC)" \ config_BUILD_CFLAGS="-O2" \ config_TARGET_CC="$(TARGET_CC)" \ <API key>="$(TARGET_CFLAGS)" \ <API key>="$(TARGET_CPPFLAGS)" \ <API key>="$(TARGET_LDFLAGS) -lreadline -lncurses" \ <API key>="-DNO_TCL=1" \ ) endef define Build/InstallDev $(INSTALL_DIR) $(1)/usr/include $(CP) $(PKG_INSTALL_DIR)/usr/include/sqlite.h $(1)/usr/include/ $(INSTALL_DIR) $(1)/usr/lib $(CP) $(PKG_INSTALL_DIR)/usr/lib/libsqlite.{a,so*} $(1)/usr/lib/ $(INSTALL_DIR) $(1)/usr/lib/pkgconfig $(CP) $(PKG_INSTALL_DIR)/usr/lib/pkgconfig/sqlite.pc $(1)/usr/lib/pkgconfig/ endef define Package/libsqlite2/install $(INSTALL_DIR) $(1)/usr/lib $(CP) $(PKG_INSTALL_DIR)/usr/lib/libsqlite.so.* $(1)/usr/lib/ endef define Package/sqlite2-cli/install $(INSTALL_DIR) $(1)/usr/bin $(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/sqlite $(1)/usr/bin/ endef $(eval $(call BuildPackage,libsqlite2)) $(eval $(call BuildPackage,sqlite2-cli))
#ifndef SCREENSHOT_H #define SCREENSHOT_H #include <QPixmap> #include <QWidget> class QCheckBox; class QGridLayout; class QGroupBox; class QHBoxLayout; class QLabel; class QPushButton; class QSpinBox; class QVBoxLayout; class Screenshot : public QWidget { Q_OBJECT public: Screenshot(); protected: void resizeEvent(QResizeEvent *event); private slots: void newScreenshot(); void saveScreenshot(); void shootScreen(); void updateCheckBox(); private: void <API key>(); void createButtonsLayout(); QPushButton *createButton(const QString &text, QWidget *receiver, const char *member); void <API key>(); QPixmap originalPixmap; QLabel *screenshotLabel; QGroupBox *optionsGroupBox; QSpinBox *delaySpinBox; QLabel *delaySpinBoxLabel; QCheckBox *<API key>; QPushButton *newScreenshotButton; QPushButton *<API key>; QPushButton *<API key>; QVBoxLayout *mainLayout; QGridLayout *<API key>; QHBoxLayout *buttonsLayout; }; #endif
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_31) on Thu May 28 10:31:01 BST 2015 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>M-Index</title> <meta name="date" content="2015-05-28"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> <script type="text/javascript" src="../script.js"></script> </head> <body> <script type="text/javascript"><! try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="M-Index"; } } catch(err) { } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar.top"> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-10.html">Prev Letter</a></li> <li><a href="index-12.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-11.html" target="_top">Frames</a></li> <li><a href="index-11.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip.navbar.top"> </a></div> <div class="contentContainer"><a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">G</a>&nbsp;<a href="index-7.html">H</a>&nbsp;<a href="index-8.html">I</a>&nbsp;<a href="index-9.html">J</a>&nbsp;<a href="index-10.html">L</a>&nbsp;<a href="index-11.html">M</a>&nbsp;<a href="index-12.html">N</a>&nbsp;<a href="index-13.html">P</a>&nbsp;<a href="index-14.html">R</a>&nbsp;<a href="index-15.html">S</a>&nbsp;<a href="index-16.html">T</a>&nbsp;<a href="index-17.html">U</a>&nbsp;<a href="index-18.html">V</a>&nbsp;<a name="I:M"> </a> <h2 class="title">M</h2> <dl> <dt><span class="memberNameLink"><a href="../View/GeoCachingPOO.html#main-java.lang.String:A-">main(String[])</a></span> - Static method in class View.<a href="../View/GeoCachingPOO.html" title="class in View">GeoCachingPOO</a></dt> <dd>&nbsp;</dd> <dt><a href="../View/Menu.html" title="class in View"><span class="typeNameLink">Menu</span></a> - Class in <a href="../View/package-summary.html">View</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../View/Menu.html#Menu-Business.Core-">Menu(Core)</a></span> - Constructor for class View.<a href="../View/Menu.html" title="class in View">Menu</a></dt> <dd>&nbsp;</dd> <dt><a href="../Data/MicroCache.html" title="class in Data"><span class="typeNameLink">MicroCache</span></a> - Class in <a href="../Data/package-summary.html">Data</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../Data/MicroCache.html#MicroCache-java.lang.String-Data.Coords-java.lang.String-java.util.HashSet-java.lang.String-int-">MicroCache(String, Coords, String, HashSet&lt;String&gt;, String, int)</a></span> - Constructor for class Data.<a href="../Data/MicroCache.html" title="class in Data">MicroCache</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../Data/MicroCache.html#MicroCache-java.lang.String-Data.Coords-java.lang.String-java.lang.String-int-">MicroCache(String, Coords, String, String, int)</a></span> - Constructor for class Data.<a href="../Data/MicroCache.html" title="class in Data">MicroCache</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../Data/MicroCache.html#MicroCache-Data.MicroCache-">MicroCache(MicroCache)</a></span> - Constructor for class Data.<a href="../Data/MicroCache.html" title="class in Data">MicroCache</a></dt> <dd>&nbsp;</dd> <dt><a href="../Exceptions/<API key>.html" title="class in Exceptions"><span class="typeNameLink"><API key></span></a> - Exception in <a href="../Exceptions/package-summary.html">Exceptions</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../Exceptions/<API key>.html#<API key>--"><API key>()</a></span> - Constructor for exception Exceptions.<a href="../Exceptions/<API key>.html" title="class in Exceptions"><API key></a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../Data/CacheList.html#MultiCache-java.lang.String-Data.Coords-java.lang.String-java.lang.String-java.util.HashMap-int-int-">MultiCache(String, Coords, String, String, HashMap&lt;Integer, Coords&gt;, int, int)</a></span> - Method in class Data.<a href="../Data/CacheList.html" title="class in Data">CacheList</a></dt> <dd>&nbsp;</dd> <dt><a href="../Data/MultiCache.html" title="class in Data"><span class="typeNameLink">MultiCache</span></a> - Class in <a href="../Data/package-summary.html">Data</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../Data/MultiCache.html#MultiCache-java.lang.String-Data.Coords-java.lang.String-java.lang.String-java.util.HashMap-int-int-">MultiCache(String, Coords, String, String, HashMap&lt;Integer, Coords&gt;, int, int)</a></span> - Constructor for class Data.<a href="../Data/MultiCache.html" title="class in Data">MultiCache</a></dt> <dd> <div class="block">Construtor basico</div> </dd> <dt><span class="memberNameLink"><a href="../Data/MultiCache.html#MultiCache-java.lang.String-java.util.HashSet-java.util.HashSet-Data.Coords-java.lang.String-java.util.HashSet-java.lang.String-int-">MultiCache(String, HashSet&lt;String&gt;, HashSet&lt;String&gt;, Coords, String, HashSet&lt;String&gt;, String, int)</a></span> - Constructor for class Data.<a href="../Data/MultiCache.html" title="class in Data">MultiCache</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../Data/MultiCache.html#MultiCache-java.lang.String-int-java.util.HashMap-java.util.HashSet-java.util.HashSet-Data.Coords-java.lang.String-java.util.HashSet-java.lang.String-int-">MultiCache(String, int, HashMap&lt;Integer, Coords&gt;, HashSet&lt;String&gt;, HashSet&lt;String&gt;, Coords, String, HashSet&lt;String&gt;, String, int)</a></span> - Constructor for class Data.<a href="../Data/MultiCache.html" title="class in Data">MultiCache</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../Data/MultiCache.html#MultiCache-Data.MultiCache-">MultiCache(MultiCache)</a></span> - Constructor for class Data.<a href="../Data/MultiCache.html" title="class in Data">MultiCache</a></dt> <dd>&nbsp;</dd> </dl> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">G</a>&nbsp;<a href="index-7.html">H</a>&nbsp;<a href="index-8.html">I</a>&nbsp;<a href="index-9.html">J</a>&nbsp;<a href="index-10.html">L</a>&nbsp;<a href="index-11.html">M</a>&nbsp;<a href="index-12.html">N</a>&nbsp;<a href="index-13.html">P</a>&nbsp;<a href="index-14.html">R</a>&nbsp;<a href="index-15.html">S</a>&nbsp;<a href="index-16.html">T</a>&nbsp;<a href="index-17.html">U</a>&nbsp;<a href="index-18.html">V</a>&nbsp;</div> <div class="bottomNav"><a name="navbar.bottom"> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-10.html">Prev Letter</a></li> <li><a href="index-12.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-11.html" target="_top">Frames</a></li> <li><a href="index-11.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip.navbar.bottom"> </a></div> </body> </html>
# This content is made available according to terms specified in __doc__ = """zenbatchload zenbatchload loads a list of devices read from a file. """ import sys import re from traceback import format_exc import socket import Globals from ZODB.POSException import ConflictError from ZODB.transact import transact from zope.component import getUtility from zope.event import notify from zExceptions import BadRequest from ZPublisher.Converters import type_converters from Products.ZenModel.interfaces import IDeviceLoader from Products.ZenUtils.ZCmdBase import ZCmdBase from Products.ZenModel.Device import Device from Products.ZenRelations.ZenPropertyManager import iszprop from Products.ZenModel.ZenModelBase import iscustprop from Products.ZenEvents.ZenEventClasses import Change_Add from Products.Zuul.catalog.events import IndexingEvent from Products.ZenUtils.Utils import unused # We import DateTime so that we can set properties of type DateTime in the batchload from DateTime import DateTime unused(DateTime) from zenoss.protocols.protobufs.zep_pb2 import SEVERITY_INFO, SEVERITY_ERROR METHODS_TO_SETTINGS = { 'setManageIp': 'manageIp', '<API key>': 'performanceMonitor', 'setTitle': 'title', 'setHWTag': 'tag', 'setHWSerialNumber': 'serialNumber', 'setProdState': 'productionState', 'setPriority': 'priority', 'setGroups': 'groupPaths', 'setSystems': 'systemPaths', # these don't have methods but were added for completeness 'setRackSlot': 'rackSlot', 'setComments': 'comments', # TODO: setHWProduct and setOSProduct (they take multiple parameters) } class BatchDeviceLoader(ZCmdBase): """ Base class wrapping around dmd.DeviceLoader """ def __init__(self, *args, **kwargs): ZCmdBase.__init__(self, *args, **kwargs) self.defaults = {} self.loader = self.dmd.DeviceLoader.loadDevice self.fqdn = socket.getfqdn() self.baseEvent = dict( device=self.fqdn, component='', agent='zenbatchload', monitor='localhost', manager=self.fqdn, severity=SEVERITY_ERROR, # Note: Change_Add events get sent to history by the event class' Zen property eventClass=Change_Add, ) # Create the list of options we want people to know about self.loader_args = dict.fromkeys( self.loader.func_code.co_varnames ) unsupportable_args = [ 'REQUEST', 'device', 'self', 'xmlrpc', 'e', 'handler', ] for opt in unsupportable_args: if opt in self.loader_args: del self.loader_args[opt] def loadDeviceList(self, args=None): """ Read through all of the files listed as arguments and return a list of device entries. @parameter args: list of filenames (uses self.args is this is None) @type args: list of strings @return: list of device specifications @rtype: list of dictionaries """ if args is None: args = self.args device_list = [] for filename in args: if filename.strip() != '': try: data = open(filename,'r').readlines() except IOError: msg = "Unable to open the file '%s'" % filename self.reportException(msg) continue temp_dev_list = self.parseDevices(data) if temp_dev_list: device_list += temp_dev_list return device_list def applyZProps(self, device, device_specs): """ Apply zProperty settings (if any) to the device. @parameter device: device to modify @type device: DMD device object @parameter device_specs: device creation dictionary @type device_specs: dictionary """ self.log.debug( "Applying zProperties..." ) # Returns a list of (key, value) pairs. # Convert it to a dictionary. dev_zprops = dict( device.zenPropertyItems() ) for zprop, value in device_specs.items(): self.log.debug( "Evaluating zProperty <%s -> %s> on %s" % (zprop, value, device.id) ) if not iszprop(zprop): self.log.debug( "Evaluating zProperty <%s -> %s> on %s: not iszprop()" % (zprop, value, device.id) ) continue if zprop in dev_zprops: try: self.log.debug( "Setting zProperty <%s -> %s> on %s (currently set to %s)" % ( zprop, value, device.id, getattr(device, zprop, 'notset')) ) device.setZenProperty(zprop, value) except BadRequest: self.log.warn( "Object %s zproperty %s is invalid or duplicate" % ( device.titleOrId(), zprop) ) except Exception, ex: self.log.warn( "Object %s zproperty %s not set (%s)" % ( device.titleOrId(), zprop, ex) ) self.log.debug( "Set zProperty <%s -> %s> on %s (now set to %s)" % ( zprop, value, device.id, getattr(device, zprop, 'notset')) ) else: self.log.warn( "The zproperty %s doesn't exist in %s" % ( zprop, device_specs.get('deviceName', device.id))) def applyCustProps(self, device, device_specs): """ Custom schema properties """ self.log.debug( "Applying custom schema properties..." ) dev_cprops = device.custPropertyMap() for cprop, value in device_specs.items(): if not iscustprop(cprop): continue matchProps = [prop for prop in dev_cprops if prop['id'] == cprop] if matchProps: ctype = matchProps[0]['type'] if ctype == 'password': ctype = 'string' if ctype in type_converters and value: value = type_converters[ctype](value) device.setZenProperty( cprop, value) else: self.log.warn( "The cproperty %s doesn't exist in %s" % ( cprop, device_specs.get('deviceName', device.id))) def addAllLGSOrganizers(self, device_specs): location = device_specs.get('setLocation') if location: self.addLGSOrganizer('Locations', (location,) ) systems = device_specs.get('setSystems') if systems: if not isinstance(systems, list) and not isinstance(systems, tuple): systems = (systems,) self.addLGSOrganizer('Systems', systems) groups = device_specs.get('setGroups') if groups: if not isinstance(groups, list) and not isinstance(groups, tuple): groups = (groups,) self.addLGSOrganizer('Groups', groups) def addLGSOrganizer(self, lgsType, paths=[]): """ Add any new locations, groups or organizers """ prefix = '/zport/dmd/' + lgsType base = getattr(self.dmd, lgsType) if hasattr(base, 'sync'): base.sync() existing = [x.getPrimaryUrlPath().replace(prefix, '') \ for x in base.getSubOrganizers()] for path in paths: if path in existing: continue try: base.manage_addOrganizer(path) except BadRequest: pass @transact def addOrganizer(self, device_specs): """ Add any organizers as required, and apply zproperties to them. """ path = device_specs.get('devicePath') baseOrg = path.split('/', 2)[1] base = getattr(self.dmd, baseOrg, None) if base is None: self.log.error("The base of path %s (%s) does not exist -- skipping", baseOrg, path) return try: org = base.getDmdObj(path) except KeyError: try: self.log.info("Creating organizer %s", path) @transact def inner(): base.manage_addOrganizer(path) inner() org = base.getDmdObj(path) except IOError: self.log.error("Unable to create organizer! Is Rabbit up and configured correctly?") sys.exit(1) self.applyZProps(org, device_specs) self.applyCustProps(org, device_specs) self.applyOtherProps(org, device_specs) def applyOtherProps(self, device, device_specs): """ Apply non-zProperty settings (if any) to the device. @parameter device: device to modify @type device: DMD device object @parameter device_specs: device creation dictionary @type device_specs: dictionary """ self.log.debug( "Applying other properties..." ) internalVars = [ 'deviceName', 'devicePath', 'comments', 'loader', 'loader_arg_keys', ] internalVars.extend(METHODS_TO_SETTINGS.itervalues()) @transact def setNamedProp(org, name, description): setattr(org, name, description) for functor, value in device_specs.items(): if iszprop(functor) or iscustprop(functor) or functor in internalVars: continue # Special case for organizers which can take a description if functor in ('description', 'address'): if hasattr(device, functor): setNamedProp(device, functor, value) continue try: self.log.debug("For %s, calling device.%s(%s)", device.id, functor, value) func = getattr(device, functor, None) if func is None or not callable(func): self.log.warn("The function '%s' for device %s is not found.", functor, device.id) elif isinstance(value, (list, tuple)): # The function either expects a list or arguments try: # arguments func(*value) except TypeError: # Try as a list func(value) else: func(value) except ConflictError: raise except Exception: msg = "Device %s device.%s(%s) failed" % (device.id, functor, value) self.reportException(msg, device.id) def runLoader(self, loader, device_specs): """ It's up to the loader now to figure out what's going on. @parameter loader: device loader @type loader: callable @parameter device_specs: device entries @type device_specs: dictionary """ argKeys = device_specs.get('loader_arg_keys', []) loader_args = {} for key in argKeys: if key in device_specs: loader_args[key] = device_specs[key] result = loader().load_device(self.dmd, **loader_args) # If the loader returns back a device object, carry # on processing if isinstance(result, Device): return result return None def processDevices(self, device_list): """ Read the input and process the devices * create the device entry * set zproperties * set custom schema properties * model the device @parameter device_list: list of device entries @type device_list: list of dictionaries @return: status of device loading @rtype: dictionary """ def transactional(f): return f if self.options.nocommit else transact(f) processed = {'processed':0, 'errors':0} @transactional def _process(device_specs): # Get the latest bits self.dmd.zport._p_jar.sync() loaderName = device_specs.get('loader') if loaderName is not None: try: orgName = device_specs['devicePath'] organizer = self.dmd.getObjByPath('dmd' + orgName) deviceLoader = getUtility(IDeviceLoader, loaderName, organizer) devobj = self.runLoader(deviceLoader, device_specs) except ConflictError: raise except Exception: devName = device_specs.get('device_specs', 'Unkown Device') msg = "Ignoring device loader issue for %s" % devName self.reportException(msg, devName, specs=str(device_specs)) processed['errors'] += 1 return else: devobj = self.getDevice(device_specs) deviceLoader = None if devobj is None: if deviceLoader is not None: processed['processed'] += 1 else: self.addAllLGSOrganizers(device_specs) self.applyZProps(devobj, device_specs) self.applyCustProps(devobj, device_specs) self.applyOtherProps(devobj, device_specs) if not self.options.nocommit and isinstance(devobj, Device): notify(IndexingEvent(devobj)) return devobj @transactional def _snmp_community(device_specs, devobj): # Discover the SNMP community if it isn't explicitly set. if 'zSnmpCommunity' not in device_specs: self.log.debug('Discovering SNMP version and community') devobj.<API key>() @transactional def _model(devobj): try: devobj.collectDevice(setlog=self.options.showModelOutput) except ConflictError: raise except Exception, ex: msg = "Modeling error for %s" % devobj.id self.reportException(msg, devobj.id, exception=str(ex)) processed['errors'] += 1 processed['processed'] += 1 for device_specs in device_list: devobj = _process(device_specs) # We need to commit in order to model, so don't bother # trying to model unless we can do both if devobj and not self.options.nocommit and not self.options.nomodel: _snmp_community(device_specs, devobj) _model(devobj) processed['total'] = len(device_list) self.reportResults(processed) return processed def reportException(self, msg, devName='', **kwargs): """ Report exceptions back to the the event console """ self.log.exception(msg) if not self.options.nocommit: evt = self.baseEvent.copy() evt.update(dict( summary=msg, traceback=format_exc() )) evt.update(kwargs) if devName: evt['device'] = devName self.dmd.ZenEventManager.sendEvent(evt) def reportResults(self, processed): """ Report the success + total counts from loading devices. """ msg = "Modeled %d of %d devices, with %d errors" % ( processed['processed'], processed['total'], processed['errors'] ) self.log.info(msg) if not self.options.nocommit: evt = self.baseEvent.copy() evt.update(dict( severity=SEVERITY_INFO, summary=msg, modeled=processed['processed'], errors=processed['errors'], total=processed['total'], )) self.dmd.ZenEventManager.sendEvent(evt) def <API key>(self, deviceName): """ Report that we added a new device. """ if not self.options.nocommit: evt = self.baseEvent.copy() evt.update(dict( severity=SEVERITY_INFO, summary= "Added new device %s" % deviceName )) self.dmd.ZenEventManager.sendEvent(evt) def getDevice(self, device_specs): """ Find or create the specified device @parameter device_specs: device creation dictionary @type device_specs: dictionary @return: device or None @rtype: DMD device object """ if 'deviceName' not in device_specs: return None name = device_specs['deviceName'] devobj = self.dmd.Devices.findDevice(name) if devobj is not None: self.log.info("Found existing device %s" % name) return devobj specs = {} for key in self.loader_args: if key in device_specs: specs[key] = device_specs[key] try: self.log.info("Creating device %s" % name) # Do NOT model at this time specs['discoverProto'] = 'none' self.loader(**specs) devobj = self.dmd.Devices.findDevice(name) if devobj is None: self.log.error("Unable to find newly created device %s -- skipping" \ % name) else: self.<API key>(name) except Exception: msg = "Unable to load %s -- skipping" % name self.reportException(msg, name) return devobj def buildOptions(self): """ Add our command-line options to the basics """ ZCmdBase.buildOptions(self) self.parser.add_option('--show_options', dest="show_options", default=False, action="store_true", help="Show the various options understood by the loader") self.parser.add_option('--sample_configs', dest="sample_configs", default=False, action="store_true", help="Show an example configuration file.") self.parser.add_option('--showModelOutput', dest="showModelOutput", default=True, action="store_false", help="Show modelling activity") self.parser.add_option('--nocommit', dest="nocommit", default=False, action="store_true", help="Don't commit changes to the ZODB. Use for verifying config file.") self.parser.add_option('--nomodel', dest="nomodel", default=False, action="store_true", help="Don't model the remote devices. Must be able to commit changes.") def parseDevices(self, data): """ From the list of strings in rawDevices, construct a list of device dictionaries, ready to load into Zenoss. @parameter data: list of strings representing device entries @type data: list of strings @return: list of parsed device entries @rtype: list of dictionaries """ if not data: return [] comment = re.compile(r'^\s* defaults = {'devicePath':"/Discovered" } finalList = [] i = 0 while i < len(data): line = data[i] line = re.sub(comment, '', line).strip() if line == '': i += 1 continue # Check for line continuation character '\' while line[-1] == '\\' and i < len(data): i += 1 line = line[:-1] + data[i] line = re.sub(comment, '', line).strip() if line[0] == '/' or line[1] == '/': # Found an organizer defaults = self.parseDeviceEntry(line, {}) if defaults is None: defaults = {'devicePath':"/Discovered" } else: defaults['devicePath'] = defaults['deviceName'] del defaults['deviceName'] self.addOrganizer(defaults) else: configs = self.parseDeviceEntry(line, defaults) if configs: finalList.append(configs) i += 1 return finalList def parseDeviceEntry(self, line, defaults): """ Build a dictionary of properties from one line's input @parameter line: string containing one device's info @type line: string @parameter defaults: dictionary of default settings @type defaults: dictionary @return: parsed device entry @rtype: dictionary """ options = [] # Note: organizers and device names can have spaces in them if line[0] in ["'", '"']: delim = line[0] eom = line.find(delim, 1) if eom == -1: self.log.error("While reading name, unable to parse" \ " the entry for %s -- skipping", line ) return None name = line[1:eom] options = line[eom+1:] else: options = line.split(None, 1) name = options.pop(0) if options: options = options.pop(0) configs = defaults.copy() configs['deviceName'] = name if options: try: # Add a newline to allow for trailing comments evalString = 'dict(' + options + '\n)' optionsDict = eval(evalString) # ZEN-202: Set values directly rather than calling methods afterwards. for method,setting in METHODS_TO_SETTINGS.iteritems(): if method in optionsDict: optionsDict[setting] = optionsDict.pop(method) configs.update(optionsDict) except Exception: self.log.error( "Unable to parse the entry for %s -- skipping" % name ) self.log.error( "Raw string: %s" % options ) return None return configs if __name__=='__main__': batchLoader = BatchDeviceLoader() if batchLoader.options.show_options: print "Options = %s" % sorted( batchLoader.loader_args.keys() ) help(batchLoader.loader) sys.exit(0) if batchLoader.options.sample_configs: print batchLoader.sample_configs sys.exit(0) device_list = batchLoader.loadDeviceList() if not device_list: batchLoader.log.warn("No device entries found to load.") sys.exit(1) batchLoader.processDevices(device_list) sys.exit(0)
<?php Function: Display UserOnline function users_online() { echo get_users_online(); } function get_users_online() { $template = UserOnline_Core::$options->templates['useronline']; $template = str_ireplace( '%PAGE_URL%', UserOnline_Core::$options->url, $template ); $template = str_ireplace( '%MOSTONLINE_COUNT%', <API key>(), $template ); $template = str_ireplace( '%MOSTONLINE_DATE%', <API key>(), $template ); return UserOnline_Template::format_count( <API key>(), 'user', $template ); } Function: Display UserOnline Count function users_online_count() { echo number_format_i18n( <API key>() ); } function <API key>() { return UserOnline_Core::<API key>(); } Function: Display Max UserOnline function most_users_online() { echo number_format_i18n( <API key>() ); } function <API key>() { return intval( UserOnline_Core::$most->count ); } Function: Display Max UserOnline Date function <API key>() { echo <API key>(); } function <API key>() { return UserOnline_Template::format_date( UserOnline_Core::$most->date ); } Function: Display Users Browsing The Site function users_browsing_site() { echo <API key>(); } function <API key>() { return UserOnline_Template::compact_list( 'site' ); } Function: Display Users Browsing The ( Current ) Page function users_browsing_page( $page_url = '' ) { echo <API key>( $page_url ); } function <API key>( $page_url = '' ) { return UserOnline_Template::compact_list( 'page', 'html', $page_url ); } Function: UserOnline Page function users_online_page() { global $wpdb; $usersonline = $wpdb->get_results( "SELECT * FROM $wpdb->useronline" ); $user_buckets = array(); foreach ( $usersonline as $useronline ) $user_buckets[$useronline->user_type][] = $useronline; $user_buckets = apply_filters( 'useronline_buckets', $user_buckets ); $counts = UserOnline_Template::get_counts( $user_buckets ); $nicetexts = array(); foreach ( array( 'user', 'member', 'guest', 'bot' ) as $user_type ) $nicetexts[$user_type] = UserOnline_Template::format_count( $counts[$user_type], $user_type ); $text = _n( 'There is <strong>%s</strong> online now: <strong>%s</strong>, <strong>%s</strong> and <strong>%s</strong>.', 'There are a total of <strong>%s</strong> online now: <strong>%s</strong>, <strong>%s</strong> and <strong>%s</strong>.', $counts['user'], 'wp-useronline' ); $output = html( 'div id="useronline-details"', html( 'p', vsprintf( $text, $nicetexts ) ) .html( 'p', UserOnline_Template::format_most_users() ) .UserOnline_Template::detailed_list( $counts, $user_buckets, $nicetexts ) ); return apply_filters( 'useronline_page', $output ); } Function Check If User Is Online function is_user_online( $user_id ) { global $wpdb; return (bool) $wpdb->get_var( $wpdb-prepare( "SELECT COUNT( * ) FROM $wpdb->useronline WHERE user_id = %d LIMIT 1", $user_id ) ); } function get_useronline_( $output, $type = 'site' ) { return UserOnline_Template::compact_list( $type, $output ); } class UserOnline_Template { private static $cache = array(); function compact_list( $type, $output = 'html', $page_url = '') { UserOnline_Core::$add_script = true; if ( !isset( self::$cache[$type] ) ) { global $wpdb; if ( 'site' == $type ) { $where = ''; } elseif ( 'page' == $type ) { if ( empty($page_url) ) $page_url = $_SERVER['REQUEST_URI']; $where = $wpdb->prepare( 'WHERE page_url = %s', $page_url ); } self::$cache[$type . $page_url] = $wpdb->get_results( "SELECT * FROM $wpdb->useronline $where" ); } $users = self::$cache[$type . $page_url]; if ( 'list' == $output ) return $users; $buckets = array(); foreach ( $users as $user ) $buckets[$user->user_type][] = $user; if ( 'buckets' == $output ) return $buckets; $counts = self::get_counts( $buckets ); if ( 'counts' == $output ) return $counts; // Template - Naming Conventions $naming = UserOnline_Core::$options->naming; // Template - User(s) Browsing Site $template = UserOnline_Core::$options->templates["browsing$type"]; // Nice Text For Users $output = self::format_count( $counts['user'], 'user', $template['text'] ); // Print Member Name $temp_member = ''; $members = @$buckets['member']; if ( $members ) { $temp_member = array(); foreach ( $members as $member ) $temp_member[] = self::format_name( $member ); $temp_member = implode( $template['separators']['members'], $temp_member ); } $output = str_ireplace( '%MEMBER_NAMES%', $temp_member, $output ); // Counts foreach ( array( 'member', 'guest', 'bot' ) as $user_type ) { if ( $counts[$user_type] > 1 ) $number = str_ireplace( '%COUNT%', number_format_i18n( $counts[$user_type] ), $naming[$user_type . 's'] ); elseif ( $counts[$user_type] == 1 ) $number = $naming[$user_type]; else $number = ''; $output = str_ireplace( "%{$user_type}S%", $number, $output ); } // SEPARATORs $separator = ( $counts['member'] && $counts['guest'] ) ? $template['separators']['guests'] : ''; $output = str_ireplace( '%GUESTS_SEPARATOR%', $separator, $output ); $separator = ( ( $counts['guest'] || $counts['member'] ) && $counts['bot'] ) ? $template['separators']['bots'] : ''; $output = str_ireplace( '%BOTS_SEPARATOR%', $separator, $output ); return $output; } function detailed_list( $counts, $user_buckets, $nicetexts ) { UserOnline_Core::$add_script = true; if ( $counts['user'] == 0 ) return html( 'h2', __( 'No one is online now.', 'wp-useronline' ) ); $_on = __( 'on', 'wp-useronline' ); $_url = __( 'url', 'wp-useronline' ); $_referral = __( 'referral', 'wp-useronline' ); $output = ''; foreach ( array( 'member', 'guest', 'bot' ) as $user_type ) { if ( !$counts[$user_type] ) continue; $count = $counts[$user_type]; $users = $user_buckets[$user_type]; $nicetext = $nicetexts[$user_type]; $output .= html( 'h2', $nicetext . ' ' . __( 'Online Now', 'wp-useronline' ) ); $i=1; foreach ( $users as $user ) { $nr = number_format_i18n( $i++ ); $name = self::format_name( $user ); $user_ip = self::format_ip( $user->user_ip ); $date = self::format_date( $user->timestamp, true ); if ( current_user_can( 'edit_users' ) || false === strpos( $user->page_url, 'wp-admin' ) ) { $page_title = esc_html( $user->page_title ); $current_link = self::format_link( $user->page_url, $_url ); $referral_link = self::format_link( $user->referral, $_referral ); } $output .= "<p><strong>#$nr - $name</strong> $user_ip $_on $date<br/>$page_title $current_link $referral_link</p>\n"; } } return $output; } private function format_link($url, $title) { if ( !empty($url) ) return '[' . html_link( esc_url($url), $title ) . ']'; return ''; } function format_ip( $ip ) { if ( current_user_can( 'edit_users' ) && !empty( $ip ) && $ip != 'unknown' ) return html( 'span', array('dir' => 'ltr'), html( 'a', array( 'href' => 'http://whois.domaintools.com/' . $ip, 'title' => gethostbyaddr( $ip ), ), $ip ) ); } function format_date( $date, $mysql = false ) { if ( $mysql ) return mysql2date( sprintf( __( '%s @ %s', 'wp-useronline' ), get_option( 'date_format' ), get_option( 'time_format' ) ), $date, true ); return date_i18n( sprintf( __( '%s @ %s', 'wp-useronline' ), get_option( 'date_format' ), get_option( 'time_format' ) ), $date ); } function format_name( $user ) { return apply_filters( '<API key>', esc_html( $user->user_name ), $user ); } function format_count( $count, $user_type, $template = false ) { $i = ( $count == 1 ) ? '' : 's'; $string = UserOnline_Core::$options->naming[$user_type . $i]; $output = str_ireplace( '%COUNT%', number_format_i18n( $count ), $string ); if ( false === $template ) return $output; return str_ireplace( '%USERS%', $output, $template ); } function format_most_users() { return sprintf( __( 'Most users ever online were <strong>%s</strong>, on <strong>%s</strong>', 'wp-useronline' ), number_format_i18n( <API key>() ), <API key>() ); } function get_counts( $buckets ) { $counts = array(); $total = 0; foreach ( array( 'member', 'guest', 'bot' ) as $user_type ) $total += $counts[$user_type] = count( @$buckets[$user_type] ); $counts['user'] = $total; return $counts; } }
Board games calendar ============== [![Build Status](https: ## Setup - `npm install` - Install MongoDB - Launch MongoDb (for example ./mongod --dbpath ~/dev/<API key>/) - `npm start` to start dev and then go `http://localhost:3000/` - `npm test` to run tests ##Frontend - Angular.js - SCSS, BEM # Guidelines - Angularjs: https://github.com/johnpapa/<API key> - CSS/SCSS: http: ## Backend - Node.js - Express - Mongodb + mongoose - forever # Guidelines - Node.js: https://github.com/alanjames1987/Node.js-Best-Practices # Mongo Shema Fixtures Sometimes you need to update your mongo database localy to get some predefined data, or update Shema. - `npm run fixtures`
/** * Compacts this ByteBuffer to be backed by a {@link ByteBuffer#buffer} of its contents' length. Contents are the bytes * between {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. Will set `offset = 0` and `limit = capacity` and * adapt {@link ByteBuffer#markedOffset} to the same relative position if set. * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset} * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit} * @returns {!ByteBuffer} this * @expose */ ByteBuffer.prototype.compact = function(begin, end) { if (typeof begin === 'undefined') begin = this.offset; if (typeof end === 'undefined') end = this.limit; if (!this.noAssert) { //? ASSERT_RANGE(); } if (begin === 0 && end === /*?= CAPACITY */) return this; // Already compacted var len = end - begin; if (len === 0) { this.buffer = EMPTY_BUFFER; //? if (!NODE || BUFFERVIEW) this.view = null; if (this.markedOffset >= 0) this.markedOffset -= begin; this.offset = 0; this.limit = 0; return this; } //? if (NODE) { var buffer = new Buffer(len); this.buffer.copy(buffer, 0, begin, end); this.buffer = buffer; //? if (BUFFERVIEW) this.view = new BufferView(buffer); //? } else { var buffer = new ArrayBuffer(len); new Uint8Array(buffer).set(new Uint8Array(this.buffer).subarray(begin, end)); this.buffer = buffer; this.view = new DataView(buffer); if (this.markedOffset >= 0) this.markedOffset -= begin; this.offset = 0; this.limit = len; return this; };
#include "qdiffusemapmaterial.h" #include "<API key>.h" #include <Qt3DRenderer/qmaterial.h> #include <Qt3DRenderer/qeffect.h> #include <Qt3DRenderer/qtexture.h> #include <Qt3DRenderer/qtechnique.h> #include <Qt3DRenderer/qshaderprogram.h> #include <Qt3DRenderer/qparameter.h> #include <Qt3DRenderer/qrenderpass.h> #include <Qt3DRenderer/qopenglfilter.h> #include <QUrl> #include <QVector3D> #include <QVector4D> QT_BEGIN_NAMESPACE namespace Qt3D { /*! \class Qt3D::<API key> \internal */ <API key>::<API key>() : QMaterialPrivate() , m_diffuseMapEffect(new QEffect()) , m_diffuseTexture(new QTexture2D()) , m_ambientParameter(new QParameter(QStringLiteral("ka"), QColor::fromRgbF(0.05f, 0.05f, 0.05f, 1.0f))) , m_diffuseParameter(new QParameter(QStringLiteral("diffuseTexture"), m_diffuseTexture)) , m_specularParameter(new QParameter(QStringLiteral("ks"), QColor::fromRgbF(0.95f, 0.95f, 0.95f, 1.0f))) , <API key>(new QParameter(QStringLiteral("shininess"), 150.0f)) , <API key>(new QParameter(QStringLiteral("lightPosition"), QVector4D(0.0f, 0.0f, 0.0f, 1.0f))) , <API key>(new QParameter(QStringLiteral("lightIntensity"), QVector3D(1.0f, 1.0f, 1.0f))) , <API key>(new QParameter(QStringLiteral("texCoordScale"), 1.0f)) , <API key>(new QTechnique()) , <API key>(new QTechnique()) , <API key>(new QTechnique()) , <API key>(new QRenderPass()) , <API key>(new QRenderPass()) , <API key>(new QRenderPass()) , <API key>(new QShaderProgram()) , <API key>(new QShaderProgram()) { m_diffuseTexture-><API key>(<API key>::Linear); m_diffuseTexture-><API key>(<API key>::LinearMipMapLinear); m_diffuseTexture->setWrapMode(QTextureWrapMode(QTextureWrapMode::Repeat)); m_diffuseTexture->setGenerateMipMaps(true); m_diffuseTexture-><API key>(16.0f); } void <API key>::init() { <API key>->setVertexShaderCode(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/shaders/gl3/diffusemap.vert")))); <API key>-><API key>(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/shaders/gl3/diffusemap.frag")))); <API key>->setVertexShaderCode(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/shaders/es2/diffusemap.vert")))); <API key>-><API key>(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/shaders/es2/diffusemap.frag")))); <API key>->openGLFilter()->setApi(QOpenGLFilter::Desktop); <API key>->openGLFilter()->setMajorVersion(3); <API key>->openGLFilter()->setMinorVersion(1); <API key>->openGLFilter()->setProfile(QOpenGLFilter::Core); <API key>->openGLFilter()->setApi(QOpenGLFilter::Desktop); <API key>->openGLFilter()->setMajorVersion(2); <API key>->openGLFilter()->setMinorVersion(0); <API key>->openGLFilter()->setProfile(QOpenGLFilter::None); <API key>->openGLFilter()->setApi(QOpenGLFilter::ES); <API key>->openGLFilter()->setMajorVersion(2); <API key>->openGLFilter()->setMinorVersion(0); <API key>->openGLFilter()->setProfile(QOpenGLFilter::None); <API key>->setShaderProgram(<API key>); <API key>->setShaderProgram(<API key>); <API key>->setShaderProgram(<API key>); <API key>->addPass(<API key>); <API key>->addPass(<API key>); <API key>->addPass(<API key>); m_diffuseMapEffect->addTechnique(<API key>); m_diffuseMapEffect->addTechnique(<API key>); m_diffuseMapEffect->addTechnique(<API key>); m_diffuseMapEffect->addParameter(m_ambientParameter); m_diffuseMapEffect->addParameter(m_diffuseParameter); m_diffuseMapEffect->addParameter(m_specularParameter); m_diffuseMapEffect->addParameter(<API key>); m_diffuseMapEffect->addParameter(<API key>); m_diffuseMapEffect->addParameter(<API key>); m_diffuseMapEffect->addParameter(<API key>); q_func()->setEffect(m_diffuseMapEffect); } /*! \class Qt3D::QDiffuseMapMaterial \brief The QDiffuseMapMaterial provides a default implementation of the phong lighting effect where the diffuse light component is read from a texture map. \inmodule Qt3DRenderer \since 5.5 The specular lighting effect is based on the combination of 3 lighting components ambient, diffuse and specular. The relative strengths of these components is controlled by means of their reflectivity coefficients which are modelled as RGB triplets: \list \li Ambient is the color that is emitted by an object without any other light source. \li Diffuse is the color that is emitted for rought surface reflections with the lights. \li Specular is the color emitted for shiny surface reflections with the lights. \li The shininess of a surface is controlled by a float property. \endlist This material uses an effect with a single render pass approach and performs per fragment lighting. Techniques are provided for OpenGL 2, OpenGL 3 or above as well as OpenGL ES 2. */ /*! Constructs a new Qt3D::QDiffuseMapMaterial instance with parent object \a parent. */ QDiffuseMapMaterial::QDiffuseMapMaterial(QNode *parent) : QMaterial(*new <API key>, parent) { Q_D(QDiffuseMapMaterial); QObject::connect(d->m_ambientParameter, SIGNAL(valueChanged()), this, SIGNAL(ambientChanged())); QObject::connect(d->m_diffuseParameter, SIGNAL(valueChanged()), this, SIGNAL(diffuseChanged())); QObject::connect(d->m_specularParameter, SIGNAL(valueChanged()), this, SIGNAL(specularChanged())); QObject::connect(d-><API key>, SIGNAL(valueChanged()), this, SIGNAL(shininessChanged())); QObject::connect(d-><API key>, SIGNAL(valueChanged()), this, SIGNAL(textureScaleChanged())); d->init(); } /*! Destroys the QDiffuseMapMaterial instance. */ QDiffuseMapMaterial::~QDiffuseMapMaterial() { } /*! \property Qt3D::QDiffuseMapMaterial::ambient Holds the current ambient color. */ QColor QDiffuseMapMaterial::ambient() const { Q_D(const QDiffuseMapMaterial); return d->m_ambientParameter->value().value<QColor>(); } /*! \property Qt3D::QDiffuseMapMaterial::specular Holds the current specular color. */ QColor QDiffuseMapMaterial::specular() const { Q_D(const QDiffuseMapMaterial); return d->m_specularParameter->value().value<QColor>(); } /*! \property Qt3D::QDiffuseMapMaterial::shininess Holds the current shininess as a float value. */ float QDiffuseMapMaterial::shininess() const { Q_D(const QDiffuseMapMaterial); return d->m_diffuseParameter->value().toFloat(); } /*! \property Qt3D::QDiffuseMapMaterial::diffuse Holds the current QTexture used as the diffuse map. By default, the diffuse texture has the following properties: \list \li Linear minification and magnification filters \li Linear mipmap with mipmapping enabled \li Repeat wrap mode \li Maximum anisotropy of 16.0 \endlist */ <API key> *QDiffuseMapMaterial::diffuse() const { Q_D(const QDiffuseMapMaterial); return d->m_diffuseParameter->value().value<<API key> *>(); } /*! \property Qt3D::QDiffuseMapMaterial::textureScale Holds the current texture scale as a float value. */ float QDiffuseMapMaterial::textureScale() const { Q_D(const QDiffuseMapMaterial); return d-><API key>->value().toFloat(); } void QDiffuseMapMaterial::setAmbient(const QColor &ambient) { Q_D(const QDiffuseMapMaterial); d->m_ambientParameter->setValue(ambient); } void QDiffuseMapMaterial::setSpecular(const QColor &specular) { Q_D(QDiffuseMapMaterial); d->m_specularParameter->setValue(specular); } void QDiffuseMapMaterial::setShininess(float shininess) { Q_D(QDiffuseMapMaterial); d-><API key>->setValue(shininess); } void QDiffuseMapMaterial::setDiffuse(<API key> *diffuseMap) { Q_D(QDiffuseMapMaterial); d->m_diffuseParameter->setValue(QVariant::fromValue(diffuseMap)); } void QDiffuseMapMaterial::setTextureScale(float textureScale) { Q_D(QDiffuseMapMaterial); d-><API key>->setValue(textureScale); } } // Qt3D QT_END_NAMESPACE
using System; using System.Collections.Generic; using WCell.Util.Logging; using WCell.Constants; using WCell.Constants.Achievements; using WCell.Constants.Factions; using WCell.RealmServer.Database; using WCell.RealmServer.Entities; using WCell.RealmServer.Handlers; using WCell.RealmServer.Database.Entities; namespace WCell.RealmServer.Factions { <summary> Represents the Reputation between a Player and all his known factions </summary> public class <API key> { private static Logger log = LogManager.<API key>(); Character m_owner; Dictionary<<API key>, Reputation> m_byIndex; public <API key>(Character chr) { m_byIndex = new Dictionary<<API key>, Reputation>(); m_owner = chr; } public int Count { get { return m_byIndex.Count; } } public Character Owner { get { return m_owner; } set { m_owner = value; } } <summary> Initializes initial Factions of the owner (used when new Character is created) </summary> public void Initialize() { var factions = FactionMgr.ById[(uint)m_owner.Faction.Entry.ParentId].Children; foreach (var faction in factions) { if (m_byIndex.ContainsKey(faction.ReputationIndex)) { log.Warn("Character {0} adding Reputation with {1} twice", m_owner, faction); } else { Create(faction.ReputationIndex); } } } <summary> Loads all Factions that this Character already knows from the DB </summary> public void Load() { foreach (var record in ReputationRecord.Load(m_owner.Record.Guid)) { var fac = FactionMgr.Get(record.ReputationIndex); if (fac != null) { if (m_byIndex.ContainsKey(record.ReputationIndex)) { log.Warn("Character {0} had Reputation with Faction {1} more than once.", m_owner, record.ReputationIndex); } else { var rep = new Reputation(record, fac); m_byIndex.Add(record.ReputationIndex, rep); } } else { log.Warn("Character {0} has saved Reputation with invalid Faction: {1}", m_owner, record.ReputationIndex); // record.DeleteAndFlush(); } } } <summary> Sends all existing factions to the Client </summary> public void ResendAllFactions() { foreach (var rep in m_byIndex.Values) { FactionHandler.<API key>(m_owner.Client, rep); } } public bool IsHostile(Faction faction) { var rep = GetOrCreate(faction.ReputationIndex); return rep != null && rep.Hostile; } public bool CanAttack(Faction faction) { var rep = GetOrCreate(faction.ReputationIndex); return rep == null || rep.Hostile; } public Reputation this[<API key> key] { get { Reputation rep; m_byIndex.TryGetValue(key, out rep); return rep; } set { // don't do anything throw new Exception("To modify the reputation with a specific faction, just modify the values of an already existing Reputation object."); } } #region Creation <summary> Returns the corresponding Reputation object. Creates a new one if the player didn't meet this faction yet. </summary> <param name="reputationIndex">The repListId of the faction</param> internal Reputation GetOrCreate(<API key> reputationIndex) { Reputation rep; if (!m_byIndex.TryGetValue(reputationIndex, out rep)) { rep = Create(reputationIndex); } return rep; } <summary> Creates a Reputation object that represents the relation to the given faction, or null </summary> <param name="factionIndex">The repListId of the faction</param> private Reputation Create(<API key> factionIndex) { var fac = FactionMgr.Get(factionIndex); if (fac != null) { return Create(fac); } return null; } <summary> Creates a Reputation object that represents the relation to the given faction, or null </summary> <param name="faction">The Faction which the Reputation should be with</param> private Reputation Create(Faction faction) { var defaultValue = <API key>(faction); var defaultFlags = <API key>(faction); var newRecord = m_owner.Record.<API key>(); var rep = new Reputation(newRecord, faction, defaultValue, defaultFlags); m_byIndex.Add(faction.ReputationIndex, rep); // For some reason, this also makes the faction visible ... FactionHandler.<API key>(m_owner.Client, rep); return rep; } private ReputationFlags <API key>(Faction faction) { var entry = faction.Entry; for (int i = 0; i < 4; i++) { if ((entry.ClassMask[i] == 0 || entry.ClassMask[i].HasAnyFlag(Owner.ClassMask)) && (entry.RaceMask[i] == 0 || entry.RaceMask[i].HasAnyFlag(Owner.RaceMask))) { return (ReputationFlags) entry.BaseFlags[i]; } } return ReputationFlags.None; } private int <API key>(Faction faction) { var entry = faction.Entry; for (int i = 0; i < 4; i++) { if ((entry.ClassMask[i] == 0 || entry.ClassMask[i].HasAnyFlag(Owner.ClassMask)) && (entry.RaceMask[i] == 0 || entry.RaceMask[i].HasAnyFlag(Owner.RaceMask))) { return entry.BaseRepValue[i]; } } return 0; } #endregion #region Value public int GetValue(<API key> reputationIndex) { Reputation rep; if (m_byIndex.TryGetValue(reputationIndex, out rep)) { return rep.Value; } return 0; } public Reputation SetValue(<API key> reputationIndex, int value) { Reputation rep = GetOrCreate(reputationIndex); if (rep != null) { SetValue(rep, value); } return rep; } public void SetValue(Reputation rep, int value) { if (rep.SetValue(value)) { //UpdateHostile(rep, rep.Hostile); } FactionHandler.<API key>(m_owner.Client, rep); } public Reputation ModValue(FactionId factionId, int value) { var faction = FactionMgr.Get(factionId); return ModValue(faction.ReputationIndex, value); } public Reputation ModValue(<API key> reputationIndex, int value) { var rep = GetOrCreate(reputationIndex); if (rep != null) { ModValue(rep, value); } return rep; } public void ModValue(Reputation rep, int value) { if (rep.SetValue(rep.Value + value)) { if (rep.StandingLevel >= StandingLevel.Honored) { Owner.Achievements.<API key>(<API key>.<API key>); } if (rep.StandingLevel >= StandingLevel.Revered) { Owner.Achievements.<API key>(<API key>.<API key>); } if (rep.StandingLevel >= StandingLevel.Exalted) { Owner.Achievements.<API key>(<API key>.<API key>); } if (value > 0) { Owner.Achievements.<API key>(<API key>.GainReputation); } } FactionHandler.<API key>(m_owner.Client, rep); } #endregion #region Standing public StandingLevel GetStandingLevel(<API key> reputationIndex) { Reputation rep; if (m_byIndex.TryGetValue(reputationIndex, out rep)) { return rep.StandingLevel; } return StandingLevel.Unknown; } #endregion #region Set/Update Hostility <summary> Only called if the player declared war </summary> public void DeclareWar(<API key> reputationIndex, bool hostile, bool sendUpdate) { var rep = GetOrCreate(reputationIndex); // impossible to declare war on your own faction if (rep.IsForcedAtPeace) return; // this shouldnt be needed because of the previous check if (rep.Faction.Group == m_owner.Faction.Group) { // can't declare war on your own faction. return; } if (rep.DeclaredWar != hostile) { rep.DeclaredWar = hostile; if (sendUpdate && rep.DeclaredWar) { FactionHandler.SendSetAtWar(m_owner.Client, rep); } } } #endregion public void SetInactive(<API key> reputationIndex, bool inactive) { var faction = GetOrCreate(reputationIndex); if (faction != null) { faction.IsInactive = true; } } #region GM's Love&Hate methods <summary> For GMs/Testers: Introduces the char to all Factions and sets Reputation to max. </summary> public void LoveAll() { foreach (Faction faction in FactionMgr.ByReputationIndex) { if (faction != null) { SetValue(faction.ReputationIndex, Reputation.Max); } } } <summary> For GMs/Testers: Introduces the char to all Factions and sets Reputation to min (oh boy are they gonna hate you). </summary> public void HateAll() { foreach (var faction in FactionMgr.ByReputationIndex) { if (faction != null) { SetValue(faction.ReputationIndex, Reputation.Min); } } } #endregion <summary> Returns the cost of this item after the reputation discount has been applied. </summary> public uint GetDiscountedCost(<API key> reputationIndex, uint cost) { var lvl = GetStandingLevel(reputationIndex); return (cost * (100 - Reputation.<API key>(lvl))) / 100; } <summary> Called when interacting with an NPC. </summary> public void OnTalkWith(NPC npc) { var reputationIndex = npc.Faction.ReputationIndex; // Does this faction even have a rep? if (reputationIndex < 0 || reputationIndex >= <API key>.End) return; Reputation rep = GetOrCreate(reputationIndex); // Faction is now visible if (!rep.IsForcedInvisible) { rep.IsVisible = true; Owner.Achievements.<API key>(<API key>.KnownFactions); // Let the client know the Faction is visible FactionHandler.SendVisible(m_owner.Client, reputationIndex); } } <summary> Increases or Decreases reputation with the given faction. </summary> <param name="factionId">Faction Id.</param> <param name="value">Amount to add or decrease</param> <returns></returns> public Reputation GainReputation(FactionId factionId, int value) { value = value + (int)Math.Round(value * m_owner.<API key> / 100.0); return ModValue(factionId, value); } public uint <API key>() { uint <API key> = 0; foreach (Reputation reputation in m_byIndex.Values) { if (reputation.IsVisible) { ++<API key>; } } return <API key>; } public uint <API key>() { uint <API key> = 0; foreach (Reputation reputation in m_byIndex.Values) { if (reputation.StandingLevel >= StandingLevel.Honored) { ++<API key>; } } return <API key>; } public uint <API key>() { uint <API key> = 0; foreach (Reputation reputation in m_byIndex.Values) { if (reputation.StandingLevel >= StandingLevel.Revered) { ++<API key>; } } return <API key>; } public uint <API key>() { uint <API key> = 0; foreach (Reputation reputation in m_byIndex.Values) { if (reputation.StandingLevel >= StandingLevel.Exalted) { ++<API key>; } } return <API key>; } } }
#include "ResultData.h" ResultData::ResultData() { clear(); } void ResultData::clear() { bTrackSuccessfull = false; id = 0; timestamp = 0; trackDurMicros = 0; ellipsePupil = cv::RotatedRect(); corneaCentre = cv::Point3d(); pupilCentre = cv::Point3d(); scenePoint = cv::Point2d(); listGlints.clear(); listContours.clear(); gazeVecStartPoint2D = cv::Point(); gazeVecEndPoint2D = cv::Point(); }
#include "config.h" #include <stdio.h> #include <string.h> #include <limits.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <utime.h> #include <sys/time.h> #include <ctype.h> #include <dirent.h> #include <errno.h> #include <wctype.h> #include <sys/vfs.h> #include "emu.h" #include "mfs.h" #include "mangle.h" #include "dos2linux.h" #include "bios.h" #include "lfn.h" #define EOS '\0' #define BACKSLASH '\\' #define SLASH '/' struct lfndir { int drive; struct mfs_dir *dir; unsigned dirattr; unsigned psp; char pattern[PATH_MAX]; char dirbase[PATH_MAX]; }; #define MAX_OPEN_DIRS 20 struct lfndir *lfndirs[MAX_OPEN_DIRS]; static unsigned long long unix_to_win_time(time_t ut) { return ((unsigned long long)ut + (369 * 365 + 89)*24*60*60ULL) * 10000000; } static time_t win_to_unix_time(unsigned long long wt) { return (wt / 10000000) - (369 * 365 + 89)*24*60*60ULL; } /* returns: NULL: error (error code in fd; 0: SFT not owned by DOSEMU otherwise it return the fd and the filename */ static char *handle_to_filename(int handle, int *fd) { struct PSP *p = MK_FP32(READ_WORDP((unsigned char *)&sda_cur_psp(sda)), 0); unsigned int filetab; unsigned int sp; unsigned char *sft; int dd, idx; struct sfttbl { FAR_PTR sftt_next; unsigned short sftt_count; unsigned char sftt_table[1]; } *spp; /* Look up the handle via the PSP */ *fd = HANDLE_INVALID; if (handle >= READ_WORDP((unsigned char *)&p->max_open_files)) return NULL; filetab = rFAR_PTR(unsigned int, READ_DWORDP((unsigned char *)&p->file_handles_ptr)); idx = READ_BYTE(filetab + handle); if (idx == 0xff) return NULL; /* Get the SFT block that contains the SFT */ sp = READ_DWORD(lol + 4); sft = NULL; while (sp != 0xffffffff) { spp = LINEAR2UNIX(rFAR_PTR(unsigned int, sp)); if (idx < READ_WORDP((unsigned char *)&spp->sftt_count)) { /* finally, point to the right entry */ sft = &spp->sftt_table[idx * sft_size]; break; } idx -= READ_WORDP((unsigned char *)&spp->sftt_count); sp = READ_DWORDP((unsigned char *)&spp->sftt_next); } if (sp == 0xffffffff) return NULL; /* do we "own" the drive? */ *fd = 0; dd = READ_WORDP((unsigned char *)&sft_device_info(sft)) & 0x0d1f; if (dd == 0 && (READ_WORDP((unsigned char *)&sft_device_info(sft)) & 0x8000)) dd = MAX_DRIVE - 1; if (dd < 0 || dd >= MAX_DRIVE || !drives[dd].root) return NULL; return sft_to_filename(sft, fd); } static int close_dirhandle(int handle) { struct lfndir *dir; if (handle < MAX_OPEN_DIRS && lfndirs[handle]) { dir = lfndirs[handle]; if (dir->dir) dos_closedir(dir->dir); free(dir); lfndirs[handle] = NULL; return 1; } return 0; } /* close all findfirst handles belonging to the current psp */ void close_dirhandles(unsigned psp) { int dirhandle; for (dirhandle = 1; dirhandle < MAX_OPEN_DIRS; dirhandle++) { struct lfndir *dir = lfndirs[dirhandle]; if (dir && dir->psp == psp) { close_dirhandle(dirhandle); } } } static int vfat_search(char *dest, char *src, char *path, int alias) { struct mfs_dir *dir = dos_opendir(path); struct mfs_dirent *de; if (dir == NULL) return 0; if (dir->dir == NULL) while ((de = dos_readdir(dir)) != NULL) { d_printf("LFN: vfat_search %s %s %s %s\n", de->d_name, de->d_long_name, src, path); if ((strcasecmp(de->d_long_name, src) == 0) || (strcasecmp(de->d_name, src) == 0)) { char *name = alias ? de->d_name : de->d_long_name; if (!name_ufs_to_dos(dest, name) || alias) { name_convert(dest, MANGLE); strupperDOS(dest); } dos_closedir(dir); return 1; } } dos_closedir(dir); return 0; } /* input: fpath = unix path current_drive = drive for DOS path alias=1: mangle, alias=0: don't mangle output: dest = DOS path */ void <API key>(char *dest, char *fpath, int current_drive, int alias) { char *src; *dest++ = current_drive + 'A'; *dest++ = ':'; *dest = '\\'; src = fpath + strlen(drives[current_drive].root); if (*src == '/') src++; while (src != NULL && *src != '\0') { char *src2 = strchr(src, '/'); if (src2 == src) break; if (src - 1 > fpath) src[-1] = '\0'; if (src2 != NULL) *src2++ = '\0'; dest++; d_printf("LFN: src=%s len=%zd\n", src, strlen(src)); if (!strcmp(src, "..") || !strcmp(src, ".")) { strcpy(dest, src); } else if (!vfat_search(dest, src, fpath, alias)) { if (!name_ufs_to_dos(dest, src) || alias) { name_convert(dest, MANGLE); strupperDOS(dest); } } dest += strlen(dest); *dest = '\\'; if (src - 1 > fpath) src[-1] = '/'; src = src2; } if (dest[-1] == ':') dest++; *dest = '\0'; } /* truename function, adapted from the FreeDOS kernel truename; (Svante Frey, James Tabor, Steffen Kaiser, Bart Oldeman, Ron Cemer) but now for LFNs */ #define PATH_ERROR goto errRet #define PATHLEN 256 #define PNE_WILDCARD 1 #define PNE_WILDCARD_STAR 2 #define addChar(c) \ { \ if (p >= dest + 256) PATH_ERROR; /* path too long */ \ *p++ = c; \ } #define CDSVALID (CDS_FLAG_REMOTE | CDS_FLAG_READY) #define CDSJOINED 0x2000 /* not in combination with NETWDRV or SUBST */ #define CDSSUBST 0x1000 /* not in combination with NETWDRV or JOINED */ static const char *get_root(const char * fname) { /* find the end */ register unsigned length = strlen(fname); char c; /* now back up to first path seperator or start */ fname += length; while (length) { length c = *--fname; if (c == '/' || c == '\\' || c == ':') { fname++; break; } } return fname; } /* helper for truename: parses either name or extension */ static int parse_name(const char **src, char **cp, char *dest) { int retval = 0; char *p = *cp; char c; while(1) switch(c=*(*src)++) { case '/': case '\\': case '\0': /* delete trailing periods and spaces */ p[0] = '\0'; while ((p[-1] == '.' || p[-1] == ' ') && p != *cp) p if (p == *cp) return -1; /* keep one trailing period if a * was encountered */ if (p[0] == '.' && (retval & PNE_WILDCARD_STAR)) p++; *cp = p; return retval; case '*': retval |= PNE_WILDCARD_STAR; /* fall through */ case '?': retval |= PNE_WILDCARD; /* fall through */ default: addChar(c); } errRet: return -1; } static int truename(char *dest, const char *src, int allowwildcards) { int i; int result; int gotAnyWildcards = 0; cds_t cds; char *p = dest; /* dynamic pointer into dest */ char *rootPos; char src0; enum { DONT_ADD, ADD, ADD_UNLESS_LAST } addSep; unsigned flags; const char *froot = get_root(src); d_printf("truename(%s)\n", src); /* In opposite of the TRUENAME shell command, an empty string is rejected by MS DOS 6 */ src0 = src[0]; if (src0 == '\0') return -FILE_NOT_FOUND; if (src0 == '\\' && src[1] == '\\') { const char *unc_src = src; /* Flag UNC paths and short circuit processing. Set current LDT */ /* to sentinel (offset 0xFFFF) for redirector processing. */ d_printf("Truename: UNC detected\n"); do { src0 = unc_src[0]; addChar(src0); unc_src++; } while (src0); WRITE_DWORDP(&sda[sda_cds_off], 0xFFFFFFFF); d_printf("Returning path: \"%s\"\n", dest); /* Flag as network - drive bits are empty but shouldn't get */ /* referenced for network with empty current_ldt. */ return 0; } /* Do we have a drive? */ if (src[1] == ':') result = toupperDOS(src0) - 'A'; else result = sda_cur_drive(sda); if (result < 0 || result >= MAX_DRIVE || result >= lol_last_drive(lol)) return -PATH_NOT_FOUND; cds = drive_cds(result); flags = cds_flags(cds); /* Entry is disabled or JOINed drives are accessable by the path only */ if (!(flags & CDSVALID) || (flags & CDSJOINED) != 0) return -PATH_NOT_FOUND; if (!drives[result].root) { if (!(flags & CDSSUBST)) return result; result = toupperDOS(cds_current_path(cds)[0]) - 'A'; if (result < 0 || result >= MAX_DRIVE || result >= lol_last_drive(lol)) return -PATH_NOT_FOUND; if (!drives[result].root) return result; flags = cds_flags(drive_cds(result)); } if (!(flags & CDS_FLAG_REMOTE)) return result; d_printf("CDS entry: #%u @%p (%u) '%s'\n", result, cds, cds_rootlen(cds), cds_current_path(cds)); WRITE_WORDP(&sda[sda_cds_off], lol_cdsfarptr(lol).offset + result * cds_record_size); dest[0] = (result & 0x1f) + 'A'; dest[1] = ':'; /* Do we have a drive? */ if (src[1] == ':') src += 2; /* check for a device */ dest[2] = '\\'; froot = get_root(src); if (is_dos_device(froot)) { if (froot == src || froot == src + 5) { if (froot == src + 5) { int j; memcpy(dest + 3, src, 5); for (j = 0; j < 5; j++) dest[3+j] = toupperDOS(dest[3+j]); if (dest[3] == '/') dest[3] = '\\'; if (dest[7] == '/') dest[7] = '\\'; } if (froot == src || memcmp(dest + 3, "\\DEV\\", 5) == 0) { /* \dev\nul -> c:/nul */ dest[2] = '/'; src = froot; } } } /* Make fully-qualified logical path */ /* register these two used characters and the \0 terminator byte */ /* we always append the current dir to stat the drive; the only exceptions are devices without paths */ rootPos = p = dest + 2; if (*p != '/') { /* i.e., it's a backslash! */ d_printf("SUBSTing from: %s\n", cds_current_path(cds)); /* What to do now: the logical drive letter will be replaced by the hidden portion of the associated path. This is necessary for NETWORK and SUBST drives. For local drives it should not harm. This is actually the reverse mechanism of JOINED drives. */ memcpy(dest, cds_current_path(cds), cds_rootlen(cds)); if (cds_flags(cds) & CDSSUBST) { /* The drive had been changed --> update the CDS pointer */ if (dest[1] == ':') { /* sanity check if this really is a local drive still */ unsigned i = toupperDOS(dest[0]) - 'A'; if (i < lol_last_drive(lol)) /* sanity check #2 */ result = (result & 0xffe0) | i; } } rootPos = p = dest + cds_rootlen(cds); *p = '\\'; /* force backslash! */ p++; if (cds_current_path(cds)[cds_rootlen(cds)] == '\0') p[0] = '\0'; else strcpy(p, cds_current_path(cds) + cds_rootlen(cds) + 1); if (*src != '\\' && *src != '/') p += strlen(p); else /* skip the absolute path marker */ src++; /* remove trailing separator */ if (p[-1] == '\\') p } /* append the path specified in src */ addSep = ADD; /* add separator */ while(*src) { /* New segment. If any wildcards in previous segment(s), this is an invalid path. */ if (gotAnyWildcards) return -PATH_NOT_FOUND; switch(*src++) { case '/': case '\\': /* skip multiple separators (duplicated slashes) */ addSep = ADD; break; case '.': /* special directory component */ switch(*src) { case '/': case '\\': case '\0': /* current path -> ignore */ addSep = ADD_UNLESS_LAST; /* If (/ or \) && no ++src --> addSep = ADD next turn */ continue; /* next char */ case '.': /* maybe ".." entry */ another_dot: switch(src[1]) { case '/': case '\\': case '\0': case '.': /* remove last path component */ while(*--p != '\\') if (p <= rootPos) /* already on root */ return -PATH_NOT_FOUND; /* the separator was removed -> add it again */ ++src; /* skip the second dot */ if (*src == '.') goto another_dot; /* If / or \, next turn will find them and assign addSep = ADD */ addSep = ADD_UNLESS_LAST; continue; /* next char */ } } default: /* normal component */ if (addSep != DONT_ADD) { /* append backslash */ addChar(*rootPos); addSep = DONT_ADD; } --src; /* first character skipped in switch() */ i = parse_name(&src, &p, dest); if (i == -1) PATH_ERROR; if (i & PNE_WILDCARD) gotAnyWildcards = TRUE; --src; /* terminator or separator was skipped */ break; } } if (gotAnyWildcards && !allowwildcards) return -PATH_NOT_FOUND; if (addSep == ADD || p == dest + 2) { /* MS DOS preserves a trailing '\\', so an access to "C:\\DOS\\" or "CDS.C\\" fails. */ /* But don't add the separator, if the last component was ".." */ /* we must also add a seperator if dest = "c:" */ addChar('\\'); } *p = '\0'; /* add the string terminator */ d_printf("Absolute logical path: \"%s\"\n", dest); /* look for any JOINed drives */ if (dest[2] != '/' && lol_njoined(lol)) { cds_t cdsp = cds_base; for(i = 0; i < lol_last_drive(lol); ++i, ++cdsp) { /* How many bytes must match */ size_t j = strlen(cds_current_path(cdsp)); /* the last component must end before the backslash offset and the path the drive is joined to leads the logical path */ if ((cds_flags(cdsp) & CDSJOINED) && (dest[j] == '\\' || dest[j] == '\0') && memcmp(dest, cds_current_path(cdsp), j) == 0) { /* JOINed drive found */ dest[0] = i + 'A'; /* index is physical here */ dest[1] = ':'; if (dest[j] == '\0') {/* Reduce to rootdirec */ dest[2] = '\\'; dest[3] = 0; /* move the relative path right behind the drive letter */ } else if (j != 2) { strcpy(dest + 2, dest + j); } result = (result & 0xffe0) | i; WRITE_WORDP(&sda[sda_cds_off], lol_cdsfarptr(lol).offset + (cdsp - cds_base)); d_printf("JOINed path: \"%s\"\n", dest); return result; } } /* nothing found => continue normally */ } d_printf("Physical path: \"%s\"\n", dest); return result; errRet: /* The error is either PATHNOTFND or FILENOTFND depending on if it is not the last component */ return strchr(src, '/') == 0 && strchr(src, '\\') == 0 ? -FILE_NOT_FOUND : -PATH_NOT_FOUND; } static inline int build_ufs_path(char *ufs, const char *path, int drive) { return build_ufs_path_(ufs, path, drive, 0); } static int lfn_error(int errorcode) { _AX = errorcode; WRITE_WORDP((unsigned char *)&sda_error_code(sda), errorcode); CARRY; return 1; } static int build_truename(char *dest, const char *src, int mode) { int dd; d_printf("LFN: build_posix_path: %s\n", src); dd = truename(dest, src, mode); if (dd < 0) { lfn_error(-dd); return -1; } if (src[0] == '\\' && src[1] == '\\') { if (strncasecmp(src, LINUX_RESOURCE, strlen(LINUX_RESOURCE)) != 0) return -2; return MAX_DRIVE - 1; } if (dd >= MAX_DRIVE || !drives[dd].root) return -2; if (!((cds_flags(drive_cds(dd))) & CDS_FLAG_REMOTE) || !drives[dd & 0x1f].root) return -2; return dd; } static int build_posix_path(char *dest, const char *src, int allowwildcards) { char filename[PATH_MAX]; int dd; dd = build_truename(filename, src, allowwildcards); if (dd < 0) return dd; build_ufs_path(dest, filename, dd); return dd; } /* wildcard match routine, losely based upon the GLIBC fnmatch routine */ static int recur_match(const char *pattern, const char *string) { unsigned char c; while ((c = *pattern++) != '\0') { if (c == '*') { while ((c = *pattern++) == '?' || c == '*') { if (c == '?' && *string++ == '\0') return 1; } if (c == '\0') /* * at end of pattern, matches anything */ return 0; for (pattern--; *string != '\0'; string++) { /* recursive search if rest of pattern matches a string part */ if (recur_match(pattern, string) == 0) return 0; } /* no match, failure... */ return 1; } else if (c == '?') { if (*string++ == '\0') return 1; } else { if ((unsigned char)pattern[-1] != toupperDOS(*string++)) return 1; } } /* at end of string, then no differences, success == 0 */ /* also check for a trailing dot so that *. works */ return !((*string == '\0') || (*string == '.' && string[1] == '\0')); } static int wild_match(const char *pattern, char *string) { char *dotpos; int rc; size_t slen = strlen(string); /* add a trailing period if there is no period, so that *.* matches */ dotpos = NULL; if (!strchr(string, '.')) { dotpos = string + slen; strcpy(dotpos, "."); slen++; } rc = recur_match(pattern, string); if (dotpos) *dotpos = '\0'; return rc; } static int lfn_sfn_match(const char *pattern, struct mfs_dirent *de, char *lfn, char *sfn) { if (!name_ufs_to_dos(lfn, de->d_long_name)) { name_convert(lfn, MANGLE); strupperDOS(lfn); } name_ufs_to_dos(sfn, de->d_name); name_convert(sfn, MANGLE); return wild_match(pattern, lfn) != 0 && wild_match(pattern, sfn) != 0; } static int getfindnext(struct mfs_dirent *de, const struct lfndir *dir) { char name_8_3[PATH_MAX]; char name_lfn[PATH_MAX]; struct stat st; char *fpath; unsigned int dest; if (lfn_sfn_match(dir->pattern, de, name_lfn, name_8_3) != 0) return 0; if (!strcmp(de->d_long_name,".") || !strcmp(de->d_long_name,"..")) { if (strlen(dir->dirbase) <= drives[dir->drive].root_len) return 0; } fpath = malloc(strlen(dir->dirbase) + 1 + strlen(de->d_long_name) + 1); strcpy(fpath, dir->dirbase); strcat(fpath, "/"); strcat(fpath, de->d_long_name); d_printf("LFN: findnext %s\n", fpath); if (stat(fpath, &st) != 0) { free(fpath); return 0; } if (st.st_mode & S_IFDIR) { if ((dir->dirattr & DIRECTORY) == 0) { free(fpath); return 0; } } else { if ((dir->dirattr >> 8) & DIRECTORY) { free(fpath); return 0; } } dest = SEGOFF2LINEAR(_ES, _DI); MEMSET_DOS(dest, 0, 0x20); WRITE_BYTE(dest, get_dos_attr(fpath,st.st_mode,is_hidden(de->d_long_name))); free(fpath); WRITE_DWORD(dest + 0x20, st.st_size); WRITE_DWORD(dest + 0x1c, st.st_size >> 32); if (_SI == 1) { u_short date, time; d_printf("LFN: using DOS date/time\n"); time_to_dos(st.st_mtime, &date, &time); WRITE_WORD(dest+0x16, date); WRITE_WORD(dest+0x14, time); time_to_dos(st.st_ctime, &date, &time); WRITE_WORD(dest+0x6, date); WRITE_WORD(dest+0x4, time); time_to_dos(st.st_atime, &date, &time); WRITE_WORD(dest+0xe, date); WRITE_WORD(dest+0xc, time); } else { unsigned long long wtime; d_printf("LFN: using WIN date/time\n"); wtime = unix_to_win_time(st.st_mtime); WRITE_DWORD(dest+0x14, wtime); WRITE_DWORD(dest+0x18, wtime >> 32); wtime = unix_to_win_time(st.st_ctime); WRITE_DWORD(dest+0x4, wtime); WRITE_DWORD(dest+0x8, wtime >> 32); wtime = unix_to_win_time(st.st_atime); WRITE_DWORD(dest+0xc, wtime); WRITE_DWORD(dest+0x10, wtime >> 32); } MEMCPY_2DOS(dest + 0x2c, name_lfn, strlen(name_lfn)+1); WRITE_BYTE(dest + 0x130, 0); strupperDOS(name_8_3); if (strcmp(name_8_3, name_lfn) != 0) { MEMCPY_2DOS(dest + 0x130, name_8_3, strlen(name_8_3)+1); } return 1; } static void call_dos_helper(int ah) { unsigned int ssp = SEGOFF2LINEAR(_SS, 0); unsigned int sp = _SP; _AH = ah; pushw(ssp, sp, _CS); pushw(ssp, sp, _IP); _SP -= 4; _CS = LFN_HELPER_SEG; _IP = LFN_HELPER_OFF; } static int wildcard_delete(char *fpath, int drive) { struct mfs_dir *dir; struct mfs_dirent *de; struct stat st; unsigned dirattr = _CX; char *pattern, *slash; int errcode; slash = strrchr(fpath, '/'); d_printf("LFN: posix:%s\n", fpath); if (slash - 2 > fpath && slash[-2] == '/' && slash[-1] == '.') slash -= 2; *slash = '\0'; if (slash == fpath) strcpy(fpath, "/"); /* XXX check for device (special dir entry) */ if (!find_file(fpath, &st, drive, NULL) || is_dos_device(fpath)) { Debug0((dbg_fd, "Get failed: '%s'\n", fpath)); return lfn_error(PATH_NOT_FOUND); } slash = fpath + strlen(fpath); dir = dos_opendir(fpath); if (dir == NULL) { Debug0((dbg_fd, "Get failed: '%s'\n", fpath)); free(dir); return lfn_error(PATH_NOT_FOUND); } pattern = malloc(strlen(slash + 1) + 1); name_ufs_to_dos(pattern, slash + 1); strupperDOS(pattern); d_printf("LFN: wildcard delete %s %s %x\n", pattern, fpath, dirattr); errcode = FILE_NOT_FOUND; while ((de = dos_readdir(dir))) { char name_8_3[PATH_MAX]; char name_lfn[PATH_MAX]; if (lfn_sfn_match(pattern, de, name_lfn, name_8_3) == 0) { *slash = '/'; strcpy(slash + 1, de->d_long_name); d_printf("LFN: wildcard delete %s\n", fpath); stat(fpath, &st); /* don't remove directories */ if (st.st_mode & S_IFDIR) continue; if ((dirattr >> 8) & DIRECTORY) continue; if (access(fpath, W_OK) == -1) { errcode = EACCES; } else { errcode = unlink(fpath) ? errno : 0; } if (errcode != 0) { Debug0((dbg_fd, "Delete failed(%s) %s\n", strerror(errcode), fpath)); free(pattern); dos_closedir(dir); if (errcode == EACCES) { return lfn_error(ACCESS_DENIED); } else { return lfn_error(FILE_NOT_FOUND); } } Debug0((dbg_fd, "Deleted %s\n", fpath)); } } free(pattern); dos_closedir(dir); if (errcode) return lfn_error(errcode); return 1; } /* the general idea here is: - convert given pathname to a Unix path by prepending the relevant "lredir" directory and flipping slashes - then we must do a case-*insensitive* and SFN matching search to find out if the path exists. This is done by find_file(); this can be a little slow but is necessary for compatibility. - following that the operation can be done directly or must be passed on to DOS using SFNs (chdir, open) using a small BIOS stub. - the SFNs are the Samba style SFNs that DOSEMU has used for as long as I can remember. */ static int mfs_lfn_(void) { char *cwd; char fpath[PATH_MAX]; char fpath2[PATH_MAX]; int drive, dirhandle = 0, rc, doserrno = FILE_NOT_FOUND; unsigned int dest = SEGOFF2LINEAR(_ES, _DI); char *src = MK_FP32(_DS, _DX); struct stat st; struct utimbuf utimbuf; size_t size; struct mfs_dirent *de; char *slash; struct lfndir *dir = NULL; d_printf("LFN: doing LFN!, AX=%x DL=%x\n", _AX, _DL); NOCARRY; if (_AH == 0x57) { char *filename; int fd; if (_AL < 4 || _AL > 7) return 0; filename = handle_to_filename(_BX, &fd); if (filename == NULL) return fd ? lfn_error(fd) : 0; if (fstat(fd, &st)) return lfn_error(HANDLE_INVALID); d_printf("LFN: handle function for BX=%x, path=%s, fd=%d\n", _BX, filename, fd); switch (_AL) { case 0x04: /* get last access date and time */ time_to_dos(st.st_atime, &_DX, &_CX); _CX = 0; break; case 0x05: /* set last access date */ utimbuf.modtime = st.st_mtime; utimbuf.actime = time_to_unix(_DX, _CX); if (dos_utime(filename, &utimbuf) != 0) return lfn_error(ACCESS_DENIED); break; case 0x06: /* get creation date/time */ time_to_dos(st.st_ctime, &_DX, &_CX); _SI = (st.st_ctime & 1) ? 100 : 0; /* fall through */ case 0x07: /* set creation date/time, impossible in Linux */ return 1; } return 1; } else if (_AH == 0x73) { unsigned int spc, bps, free, tot; if (_AL != 3) return 0; d_printf("LFN: Get disk space %s\n", src); drive = build_posix_path(fpath, src, 0); if (drive < 0) return drive + 2; if (!find_file(fpath, &st, drive, NULL)|| !S_ISDIR(st.st_mode)) return lfn_error(PATH_NOT_FOUND); if (!dos_get_disk_space(fpath, &free, &tot, &spc, &bps)) return lfn_error(PATH_NOT_FOUND); WRITE_DWORD(dest, 0x24); WRITE_DWORD(dest + 0x4, spc); WRITE_DWORD(dest + 0x8, bps); WRITE_DWORD(dest + 0xc, free); WRITE_DWORD(dest + 0x10, tot); WRITE_DWORD(dest + 0x14, free * spc); WRITE_DWORD(dest + 0x18, tot * spc); WRITE_DWORD(dest + 0x1c, free); WRITE_DWORD(dest + 0x20, tot); return 1; } /* else _AH == 0x71 */ switch (_AL) { case 0x0D: /* reset drive, nothing to do */ break; case 0x39: /* mkdir */ case 0x3a: /* rmdir */ d_printf("LFN: %sdir %s\n", _AL == 0x39 ? "mk" : "rm", src); drive = build_truename(fpath, src, 0); if (drive < 0) return drive + 2; rc = (_AL == 0x39 ? dos_mkdir : dos_rmdir)(fpath, drive, 1); if (rc) return lfn_error(rc); break; case 0x3b: /* chdir */ { char *d = MK_FP32(BIOSSEG, LFN_string - (char *)bios_f000); Debug0((dbg_fd, "set directory to: %s\n", src)); d_printf("LFN: chdir %s %zd\n", src, strlen(src)); drive = build_posix_path(fpath, src, 0); if (drive < 0) return drive + 2; if (!find_file(fpath, &st, drive, NULL)|| !S_ISDIR(st.st_mode)) return lfn_error(PATH_NOT_FOUND); <API key>(d, fpath, drive, 1); d_printf("LFN: New CWD will be %s\n", d); call_dos_helper(0x3b); break; } case 0x41: /* remove file */ drive = build_posix_path(fpath, src, _SI); if (drive < 0) return drive + 2; if (drives[drive].read_only) return lfn_error(ACCESS_DENIED); if (is_dos_device(fpath)) return lfn_error(FILE_NOT_FOUND); if (_SI == 1) return wildcard_delete(fpath, drive); if (!find_file(fpath, &st, drive, &doserrno)) return lfn_error(doserrno); d_printf("LFN: deleting %s\n", fpath); if (unlink(fpath) != 0) return lfn_error(FILE_NOT_FOUND); break; case 0x43: /* get/set file attributes */ d_printf("LFN: attribute %s %d\n", src, _BL); drive = build_posix_path(fpath, src, 0); if (drive < 0) return drive + 2; if (drives[drive].read_only && (_BL < 8) && (_BL & 1)) return lfn_error(ACCESS_DENIED); if (!find_file(fpath, &st, drive, &doserrno) || is_dos_device(fpath)) { Debug0((dbg_fd, "Get failed: '%s'\n", fpath)); return lfn_error(doserrno); } utimbuf.actime = st.st_atime; utimbuf.modtime = st.st_mtime; switch (_BL) { case 0: /* retrieve attributes */ _CX = get_dos_attr(fpath, st.st_mode,is_hidden(fpath)); break; case 1: /* set attributes */ if (set_dos_attr(fpath, st.st_mode, _CX) != 0) return lfn_error(ACCESS_DENIED); break; case 2: /* get physical size of uncompressed file */ _DX = st.st_size >> 16; _AX = st.st_size & 0xffff; break; case 3: /* set last write date/time */ utimbuf.modtime = time_to_unix(_DI, _CX); if (dos_utime(fpath, &utimbuf) != 0) return lfn_error(ACCESS_DENIED); break; case 4: /* get last write date/time */ time_to_dos(st.st_mtime, &_DI, &_CX); break; case 5: /* set last access date */ utimbuf.actime = time_to_unix(_DI, _CX); if (dos_utime(fpath, &utimbuf) != 0) return lfn_error(ACCESS_DENIED); break; case 6: /* get last access date */ { unsigned short scratch; time_to_dos(st.st_atime, &_DI, &scratch); break; } case 7: /* set creation date/time, impossible in Linux */ break; case 8: /* get creation date/time */ time_to_dos(st.st_ctime, &_DI, &_CX); _SI = (st.st_ctime & 1) ? 100 : 0; break; } break; case 0x47: /* get current directory */ if (_DL == 0) drive = sda_cur_drive(sda); else drive = _DL - 1; if (drive < 0 || drive >= MAX_DRIVE) return lfn_error(DISK_DRIVE_INVALID); if (!drives[drive].root) return 0; cwd = cds_current_path(drive_cds(drive)); dest = SEGOFF2LINEAR(_DS, _SI); build_ufs_path(fpath, cwd, drive); d_printf("LFN: getcwd %s %s\n", cwd, fpath); find_file(fpath, &st, drive, NULL); d_printf("LFN: getcwd %s %s\n", cwd, fpath); d_printf("LFN: %p %d %#x %s\n", drive_cds(drive), drive, dest, fpath+drives[drive].root_len); <API key>(fpath2, fpath, drive, 0); MEMCPY_2DOS(dest, fpath2 + 3, strlen(fpath2 + 3) + 1); break; case 0x4e: /* find first */ { drive = build_posix_path(fpath, src, 1); if (drive < 0) return drive + 2; slash = strrchr(fpath, '/'); d_printf("LFN: posix:%s\n", fpath); *slash++ = '\0'; /* note: DJGPP doesn't like "0" as a directory handle */ for (dirhandle = 1; dirhandle < MAX_OPEN_DIRS; dirhandle++) if (lfndirs[dirhandle] == NULL) break; if (dirhandle == MAX_OPEN_DIRS) { d_printf("LFN: too many dirs open\n"); return lfn_error(NO_MORE_FILES); } dir = malloc(sizeof *dir); if (slash == fpath + 1) strcpy(dir->dirbase, "/"); else strcpy(dir->dirbase, fpath); dir->dirattr = _CX; dir->drive = drive; dir->psp = sda_cur_psp(sda); name_ufs_to_dos(dir->pattern, slash); strupperDOS(dir->pattern); if (((_CX & (VOLUME_LABEL|DIRECTORY)) == VOLUME_LABEL) && (strcmp(slash, "*.*") == 0 || strcmp(slash, "*") == 0)) { char lfn[260]; dest = SEGOFF2LINEAR(_ES, _DI); MEMSET_DOS(dest, 0, 0x20); WRITE_BYTE(dest, VOLUME_LABEL); get_volume_label(NULL, NULL, lfn, drive); MEMCPY_2DOS(dest + 0x2c, lfn, strlen(lfn) + 1); WRITE_BYTE(dest + 0x130, 0); d_printf("LFN: get volume label: %s\n", lfn); lfndirs[dirhandle] = dir; dir->dir = NULL; _AX = dirhandle; _CX = 0; return 1; } /* XXX check for device (special dir entry) */ if (!find_file(dir->dirbase, &st, drive, NULL) || is_dos_device(fpath)) { Debug0((dbg_fd, "Get failed: '%s'\n", fpath)); free(dir); return lfn_error(NO_MORE_FILES); } dir->dir = dos_opendir(dir->dirbase); if (dir->dir == NULL) { Debug0((dbg_fd, "Get failed: '%s'\n", fpath)); free(dir); return lfn_error(NO_MORE_FILES); } d_printf("LFN: findfirst %s %s %s %x\n", slash, src, dir->dirbase, _CX); lfndirs[dirhandle] = dir; /* fall through! */ } case 0x4f: /* find next */ case 0xa2: { if (_AL != 0x4e && _BX < MAX_OPEN_DIRS) { dirhandle = _BX; dir = lfndirs[dirhandle]; } if (dir == NULL) return 0; if (dir->dir == NULL) return lfn_error(NO_MORE_FILES); do { de = dos_readdir(dir->dir); if (de == NULL) { dos_closedir(dir->dir); dir->dir = NULL; if (_AL == 0x4e) close_dirhandle(dirhandle); return lfn_error(NO_MORE_FILES); } d_printf("LFN: findnext %s %x\n", de->d_long_name, dir->dirattr); } while (!getfindnext(de, dir)); if (_AL != 0x4e) _AX = 0x4f00 + dirhandle; else _AX = dirhandle; _CX = 0; break; } case 0x56: /* rename file */ { int drive2, rc; const char *d = MK_FP32(_ES, _DI); d_printf("LFN: rename to %s\n", d); drive = build_truename(fpath2, d, 0); if (drive < 0) return drive + 2; d_printf("LFN: rename from %s\n", src); drive2 = build_truename(fpath, src, 0); if (drive2 < 0) return drive2 + 2; if (drive != drive2) return lfn_error(NOT_SAME_DEV); rc = dos_rename(fpath, fpath2, drive, 1); if (rc) return lfn_error(rc); break; } case 0x60: /* truename */ { int i; char filename[PATH_MAX]; src = MK_FP32(_DS, _SI); d_printf("LFN: truename %s, cl=%d\n", src, _CL); i = 0; if (src[0] && src[1] == ':') i = 2; for (; src[i]; i++) { if (!VALID_DOS_PCHAR(src + i) && strchr("\\/.",src[i]) == 0 && (_CL == 2 || strchr(" +,;=[]",src[i])==0)) { return lfn_error(FILE_NOT_FOUND); } } drive = build_truename(filename, src, !_CL); if (drive < 0) return drive + 2; d_printf("LFN: %s %s\n", fpath, drives[drive].root); if (_CL == 1 || _CL == 2) { build_ufs_path(fpath, filename, drive); if (!find_file(fpath, &st, drive, &doserrno)) return lfn_error(doserrno); <API key>(filename, fpath, drive, 2 - _CL); } else { strupperDOS(filename); } d_printf("LFN: %s %s\n", filename, drives[drive].root); MEMCPY_2DOS(dest, filename, strlen(filename) + 1); break; } case 0x6c: /* create/open */ { char *d = MK_FP32(BIOSSEG, LFN_string - (char *)bios_f000); src = MK_FP32(_DS, _SI); d_printf("LFN: open %s\n", src); drive = build_posix_path(fpath, src, 0); if (drive < 0) return drive + 2; if (is_dos_device(fpath)) { strcpy(d, strrchr(fpath, '/') + 1); } else { slash = strrchr(fpath, '/'); strcpy(fpath2, slash); *slash = '\0'; if (slash != fpath && !find_file(fpath, &st, drive, NULL)) return lfn_error(PATH_NOT_FOUND); strcat(fpath, fpath2); if (!find_file(fpath, &st, drive, NULL) && (_DX & 0x10)) { int fd; if (drives[drive].read_only) return lfn_error(ACCESS_DENIED); fd = open(fpath, (O_RDWR | O_CREAT), get_unix_attr(0664, _CL | ARCHIVE_NEEDED)); if (fd < 0) { d_printf("LFN: creat problem: %o %s %s\n", get_unix_attr(0644, _CX), fpath, strerror(errno)); return lfn_error(ACCESS_DENIED); } set_fat_attr(fd, _CL | ARCHIVE_NEEDED); d_printf("LFN: open: created %s\n", fpath); close(fd); _AL = 1; /* flags creation to DOS helper */ } else { _AL = 0; } <API key>(d, fpath, drive, 1); } call_dos_helper(0x6c); break; } case 0xa0: /* get volume info */ drive = build_posix_path(fpath, src, 0); if (drive < 0) return drive + 2; size = _CX; _AX = 0; _BX = 0x4002; _CX = 255; _DX = 260; if (size >= 4) MEMCPY_2DOS(dest, "MFS", 4); break; case 0xa1: /* findclose */ d_printf("LFN: findclose %x\n", _BX); return close_dirhandle(_BX); case 0xa6: { /* get file info by handle */ int fd; char *filename; unsigned long long wtime; unsigned int buffer = SEGOFF2LINEAR(_DS, _DX); d_printf("LFN: get file info by handle %x\n", _BX); filename = handle_to_filename(_BX, &fd); if (filename == NULL) return fd ? lfn_error(fd) : 0; if (fstat(fd, &st)) return lfn_error(HANDLE_INVALID); d_printf("LFN: handle function for BX=%x, path=%s, fd=%d\n", _BX, filename, fd); WRITE_DWORD(buffer, get_dos_attr_fd(fd, st.st_mode, is_hidden(filename))); wtime = unix_to_win_time(st.st_ctime); WRITE_DWORD(buffer + 4, wtime); WRITE_DWORD(buffer + 8, wtime >> 32); wtime = unix_to_win_time(st.st_atime); WRITE_DWORD(buffer + 0xc, wtime); WRITE_DWORD(buffer + 0x10, wtime >> 32); wtime = unix_to_win_time(st.st_mtime); WRITE_DWORD(buffer + 0x14, wtime); WRITE_DWORD(buffer + 0x18, wtime >> 32); WRITE_DWORD(buffer + 0x1c, st.st_dev); /*volume serial number*/ WRITE_DWORD(buffer + 0x20, (unsigned long long)st.st_size >> 32); WRITE_DWORD(buffer + 0x24, st.st_size); WRITE_DWORD(buffer + 0x28, st.st_nlink); /* fileid*/ WRITE_DWORD(buffer + 0x2c, (unsigned long long)st.st_ino >> 32); WRITE_DWORD(buffer + 0x30, st.st_ino); return 0; } case 0xa7: /* file time to DOS time and v.v. */ if (_BL == 0) { src = MK_FP32(_DS, _SI); time_to_dos( win_to_unix_time(*(unsigned long long *)src), &_DX, &_CX); _BH = 0; } else { unsigned long long wtime; wtime = unix_to_win_time(time_to_unix(_DX, _CX)); WRITE_DWORD(dest, wtime); WRITE_DWORD(dest + 4, wtime >> 32); } break; case 0xa8: /* generate short filename */ { src = MK_FP32(_DS, _SI); StrnCpy(fpath, src, sizeof(fpath) - 1); name_convert(fpath, MANGLE); strupperDOS(fpath); if (_DH == 0) { char d[8+3]; extract_filename(fpath, d, d + 8); MEMCPY_2DOS(dest, fpath, 11); } else MEMCPY_2DOS(dest, fpath, strlen(fpath) + 1); d_printf("LFN: name convert %s %s %x\n", src, fpath, _DH); break; } case 0xa9: /* server create or open file */ case 0xaa: /* create/terminate/query subst */ default: return 0; } return 1; /* finished: back to caller */ } int mfs_lfn(void) { int carry, ret; carry = isset_CF(); ret = mfs_lfn_(); /* preserve carry if we forward the LFN request */ if (ret == 0 && carry) CARRY; return ret; }
<?php class Text_Diff { /** * Array of changes. * * @var array */ var $_edits; /** * Computes diffs between sequences of strings. * * @param string $engine Name of the diffing engine to use. 'auto' * will automatically select the best. * @param array $params Parameters to pass to the diffing engine. * Normally an array of two arrays, each * containing the lines from a file. */ function Text_Diff($engine, $params) { // Backward compatibility workaround. if (!is_string($engine)) { $params = array($engine, $params); $engine = 'auto'; } if ($engine == 'auto') { $engine = extension_loaded('xdiff') ? 'xdiff' : 'native'; } else { $engine = basename($engine); } global $topdir; require_once $topdir.'include/lib/text_diff/Diff/Engine/' . $engine . '.php'; $class = 'Text_Diff_Engine_' . $engine; $diff_engine = new $class(); $this->_edits = <API key>(array($diff_engine, 'diff'), $params); } /** * Returns the array of differences. */ function getDiff() { return $this->_edits; } /** * Computes a reversed diff. * * Example: * <code> * $diff = new Text_Diff($lines1, $lines2); * $rev = $diff->reverse(); * </code> * * @return Text_Diff A Diff object representing the inverse of the * original diff. Note that we purposely don't return a * reference here, since this essentially is a clone() * method. */ function reverse() { if (version_compare(zend_version(), '2', '>')) { $rev = clone($this); } else { $rev = $this; } $rev->_edits = array(); foreach ($this->_edits as $edit) { $rev->_edits[] = $edit->reverse(); } return $rev; } /** * Checks for an empty diff. * * @return boolean True if two sequences were identical. */ function isEmpty() { foreach ($this->_edits as $edit) { if (!is_a($edit, 'Text_Diff_Op_copy')) { return false; } } return true; } /** * Computes the length of the Longest Common Subsequence (LCS). * * This is mostly for diagnostic purposes. * * @return integer The length of the LCS. */ function lcs() { $lcs = 0; foreach ($this->_edits as $edit) { if (is_a($edit, 'Text_Diff_Op_copy')) { $lcs += count($edit->orig); } } return $lcs; } /** * Gets the original set of lines. * * This reconstructs the $from_lines parameter passed to the constructor. * * @return array The original sequence of strings. */ function getOriginal() { $lines = array(); foreach ($this->_edits as $edit) { if ($edit->orig) { array_splice($lines, count($lines), 0, $edit->orig); } } return $lines; } /** * Gets the final set of lines. * * This reconstructs the $to_lines parameter passed to the constructor. * * @return array The sequence of strings. */ function getFinal() { $lines = array(); foreach ($this->_edits as $edit) { if ($edit->final) { array_splice($lines, count($lines), 0, $edit->final); } } return $lines; } /** * Removes trailing newlines from a line of text. This is meant to be used * with array_walk(). * * @param string $line The line to trim. * @param integer $key The index of the line in the array. Not used. */ function trimNewlines(&$line, $key) { $line = str_replace(array("\n", "\r"), '', $line); } /** * Determines the location of the system temporary directory. * * @static * * @access protected * * @return string A directory name which can be used for temp files. * Returns false if one could not be found. */ function _getTempDir() { $tmp_locations = array('/tmp', '/var/tmp', 'c:\WUTemp', 'c:\temp', 'c:\windows\temp', 'c:\winnt\temp'); /* Try PHP's upload_tmp_dir directive. */ $tmp = ini_get('upload_tmp_dir'); /* Otherwise, try to determine the TMPDIR environment variable. */ if (!strlen($tmp)) { $tmp = getenv('TMPDIR'); } /* If we still cannot determine a value, then cycle through a list of * preset possibilities. */ while (!strlen($tmp) && count($tmp_locations)) { $tmp_check = array_shift($tmp_locations); if (@is_dir($tmp_check)) { $tmp = $tmp_check; } } /* If it is still empty, we have failed, so return false; otherwise * return the directory determined. */ return strlen($tmp) ? $tmp : false; } /** * Checks a diff for validity. * * This is here only for debugging purposes. */ function _check($from_lines, $to_lines) { if (serialize($from_lines) != serialize($this->getOriginal())) { trigger_error("Reconstructed original doesn't match", E_USER_ERROR); } if (serialize($to_lines) != serialize($this->getFinal())) { trigger_error("Reconstructed final doesn't match", E_USER_ERROR); } $rev = $this->reverse(); if (serialize($to_lines) != serialize($rev->getOriginal())) { trigger_error("Reversed original doesn't match", E_USER_ERROR); } if (serialize($from_lines) != serialize($rev->getFinal())) { trigger_error("Reversed final doesn't match", E_USER_ERROR); } $prevtype = null; foreach ($this->_edits as $edit) { if ($prevtype == get_class($edit)) { trigger_error("Edit sequence is non-optimal", E_USER_ERROR); } $prevtype = get_class($edit); } return true; } } /** * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> */ class Text_MappedDiff extends Text_Diff { /** * Computes a diff between sequences of strings. * * This can be used to compute things like case-insensitve diffs, or diffs * which ignore changes in white-space. * * @param array $from_lines An array of strings. * @param array $to_lines An array of strings. * @param array $mapped_from_lines This array should have the same size * number of elements as $from_lines. The * elements in $mapped_from_lines and * $mapped_to_lines are what is actually * compared when computing the diff. * @param array $mapped_to_lines This array should have the same number * of elements as $to_lines. */ function Text_MappedDiff($from_lines, $to_lines, $mapped_from_lines, $mapped_to_lines) { assert(count($from_lines) == count($mapped_from_lines)); assert(count($to_lines) == count($mapped_to_lines)); parent::Text_Diff($mapped_from_lines, $mapped_to_lines); $xi = $yi = 0; for ($i = 0; $i < count($this->_edits); $i++) { $orig = &$this->_edits[$i]->orig; if (is_array($orig)) { $orig = array_slice($from_lines, $xi, count($orig)); $xi += count($orig); } $final = &$this->_edits[$i]->final; if (is_array($final)) { $final = array_slice($to_lines, $yi, count($final)); $yi += count($final); } } } } /** * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> * * @access private */ class Text_Diff_Op { var $orig; var $final; function &reverse() { trigger_error('Abstract method', E_USER_ERROR); } function norig() { return $this->orig ? count($this->orig) : 0; } function nfinal() { return $this->final ? count($this->final) : 0; } } /** * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> * * @access private */ class Text_Diff_Op_copy extends Text_Diff_Op { function Text_Diff_Op_copy($orig, $final = false) { if (!is_array($final)) { $final = $orig; } $this->orig = $orig; $this->final = $final; } function &reverse() { $reverse = &new Text_Diff_Op_copy($this->final, $this->orig); return $reverse; } } /** * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> * * @access private */ class Text_Diff_Op_delete extends Text_Diff_Op { function Text_Diff_Op_delete($lines) { $this->orig = $lines; $this->final = false; } function &reverse() { $reverse = &new Text_Diff_Op_add($this->orig); return $reverse; } } /** * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> * * @access private */ class Text_Diff_Op_add extends Text_Diff_Op { function Text_Diff_Op_add($lines) { $this->final = $lines; $this->orig = false; } function &reverse() { $reverse = &new Text_Diff_Op_delete($this->final); return $reverse; } } /** * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> * * @access private */ class Text_Diff_Op_change extends Text_Diff_Op { function Text_Diff_Op_change($orig, $final) { $this->orig = $orig; $this->final = $final; } function &reverse() { $reverse = &new Text_Diff_Op_change($this->final, $this->orig); return $reverse; } }
#include <stdarg.h> #include <linux/module.h> #include <linux/sched.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/stddef.h> #include <linux/unistd.h> #include <linux/user.h> #include <linux/delay.h> #include <linux/reboot.h> #include <linux/interrupt.h> #include <linux/kallsyms.h> #include <linux/init.h> #include <linux/cpu.h> #include <linux/elfcore.h> #include <linux/pm.h> #include <linux/tick.h> #include <linux/utsname.h> #include <linux/uaccess.h> #include <asm/leds.h> #include <asm/processor.h> #include <asm/system.h> #include <asm/thread_notify.h> #include <asm/stacktrace.h> #include <asm/mach/time.h> #ifdef <API key> #include <linux/kernel_sec_common.h> struct pt_regs <API key>; #endif static const char *processor_modes[] = { "USER_26", "FIQ_26" , "IRQ_26" , "SVC_26" , "UK4_26" , "UK5_26" , "UK6_26" , "UK7_26" , "UK8_26" , "UK9_26" , "UK10_26", "UK11_26", "UK12_26", "UK13_26", "UK14_26", "UK15_26", "USER_32", "FIQ_32" , "IRQ_32" , "SVC_32" , "UK4_32" , "UK5_32" , "UK6_32" , "ABT_32" , "UK8_32" , "UK9_32" , "UK10_32", "UND_32" , "UK12_32", "UK13_32", "UK14_32", "SYS_32" }; static const char *isa_modes[] = { "ARM" , "Thumb" , "Jazelle", "ThumbEE" }; extern void setup_mm_for_reboot(char mode); static volatile int hlt_counter; #include <mach/system.h> void disable_hlt(void) { hlt_counter++; } EXPORT_SYMBOL(disable_hlt); void enable_hlt(void) { hlt_counter } EXPORT_SYMBOL(enable_hlt); static int __init nohlt_setup(char *__unused) { hlt_counter = 1; return 1; } static int __init hlt_setup(char *__unused) { hlt_counter = 0; return 1; } __setup("nohlt", nohlt_setup); __setup("hlt", hlt_setup); void arm_machine_restart(char mode, const char *cmd) { /* * Clean and disable cache, and turn off interrupts */ cpu_proc_fin(); /* * Tell the mm system that we are going to reboot - * we may need it to insert some 1:1 mappings so that * soft boot works. */ setup_mm_for_reboot(mode); #if 1 #ifdef <API key> /* Clear the magic number because it's normal reboot */ <API key>(); #endif writel(0x12345678, S5P_INFORM5); /* Reset */ #endif /* * Now call the architecture specific reboot code. */ arch_reset(mode, cmd); /* * Whoops - the architecture was unable to reboot. * Tell the user! */ mdelay(1000); printk("Reboot failed -- System halted\n"); while (1); } /* * Function pointers to optional machine specific functions */ void (*pm_power_off)(void); EXPORT_SYMBOL(pm_power_off); void (*arm_pm_restart)(char str, const char *cmd) = arm_machine_restart; EXPORT_SYMBOL_GPL(arm_pm_restart); /* * This is our default idle handler. We need to disable * interrupts here to ensure we don't miss a wakeup call. */ static void default_idle(void) { if (!need_resched()) arch_idle(); local_irq_enable(); } void (*pm_idle)(void) = default_idle; EXPORT_SYMBOL(pm_idle); /* * The idle thread, has rather strange semantics for calling pm_idle, * but this is what x86 does and we need to do the same, so that * things like cpuidle get called in the same way. The only difference * is that we always respect 'hlt_counter' to prevent low power idle. */ void cpu_idle(void) { local_fiq_enable(); /* endless idle loop with no priority at all */ while (1) { <API key>(1); leds_event(led_idle_start); while (!need_resched()) { #ifdef CONFIG_HOTPLUG_CPU if (cpu_is_offline(smp_processor_id())) cpu_die(); #endif local_irq_disable(); if (hlt_counter) { local_irq_enable(); cpu_relax(); } else { <API key>(); pm_idle(); <API key>(); /* * This will eventually be removed - pm_idle * functions should always return with IRQs * enabled. */ WARN_ON(irqs_disabled()); local_irq_enable(); } } leds_event(led_idle_end); <API key>(); <API key>(); schedule(); preempt_disable(); } } static char reboot_mode = 'h'; int __init reboot_setup(char *str) { reboot_mode = str[0]; return 1; } __setup("reboot=", reboot_setup); void machine_halt(void) { } void machine_power_off(void) { if (pm_power_off) pm_power_off(); } void machine_restart(char *cmd) { arm_pm_restart(reboot_mode, cmd); } /* * dump a block of kernel memory from around the given address */ static void show_data(unsigned long addr, int nbytes, const char *name) { int i, j; int nlines; u32 *p; /* * don't attempt to dump non-kernel addresses or * values that are probably just small negative numbers */ if (addr < PAGE_OFFSET || addr > -256UL) return; printk("\n%s: %#lx:\n", name, addr); /* * round address down to a 32 bit boundary * and always dump a multiple of 32 bytes */ p = (u32 *)(addr & ~(sizeof(u32) - 1)); nbytes += (addr & (sizeof(u32) - 1)); nlines = (nbytes + 31) / 32; for (i = 0; i < nlines; i++) { /* * just display low 16 bits of address to keep * each line of the dump < 80 characters */ printk("%04lx ", (unsigned long)p & 0xffff); for (j = 0; j < 8; j++) { u32 data; if (<API key>(p, data)) { printk(" ********"); } else { printk(" %08x", data); } ++p; } printk("\n"); } } static void <API key>(struct pt_regs *regs, int nbytes) { mm_segment_t fs; fs = get_fs(); set_fs(KERNEL_DS); show_data(regs->ARM_pc - nbytes, nbytes * 2, "PC"); show_data(regs->ARM_lr - nbytes, nbytes * 2, "LR"); show_data(regs->ARM_sp - nbytes, nbytes * 2, "SP"); show_data(regs->ARM_ip - nbytes, nbytes * 2, "IP"); show_data(regs->ARM_fp - nbytes, nbytes * 2, "FP"); show_data(regs->ARM_r0 - nbytes, nbytes * 2, "R0"); show_data(regs->ARM_r1 - nbytes, nbytes * 2, "R1"); show_data(regs->ARM_r2 - nbytes, nbytes * 2, "R2"); show_data(regs->ARM_r3 - nbytes, nbytes * 2, "R3"); show_data(regs->ARM_r4 - nbytes, nbytes * 2, "R4"); show_data(regs->ARM_r5 - nbytes, nbytes * 2, "R5"); show_data(regs->ARM_r6 - nbytes, nbytes * 2, "R6"); show_data(regs->ARM_r7 - nbytes, nbytes * 2, "R7"); show_data(regs->ARM_r8 - nbytes, nbytes * 2, "R8"); show_data(regs->ARM_r9 - nbytes, nbytes * 2, "R9"); show_data(regs->ARM_r10 - nbytes, nbytes * 2, "R10"); set_fs(fs); } void __show_regs(struct pt_regs *regs) { unsigned long flags; char buf[64]; printk("CPU: %d %s (%s %.*s)\n", <API key>(), print_tainted(), init_utsname()->release, (int)strcspn(init_utsname()->version, " "), init_utsname()->version); print_symbol("PC is at %s\n", instruction_pointer(regs)); print_symbol("LR is at %s\n", regs->ARM_lr); printk("pc : [<%08lx>] lr : [<%08lx>] psr: %08lx\n" "sp : %08lx ip : %08lx fp : %08lx\n", regs->ARM_pc, regs->ARM_lr, regs->ARM_cpsr, regs->ARM_sp, regs->ARM_ip, regs->ARM_fp); printk("r10: %08lx r9 : %08lx r8 : %08lx\n", regs->ARM_r10, regs->ARM_r9, regs->ARM_r8); printk("r7 : %08lx r6 : %08lx r5 : %08lx r4 : %08lx\n", regs->ARM_r7, regs->ARM_r6, regs->ARM_r5, regs->ARM_r4); printk("r3 : %08lx r2 : %08lx r1 : %08lx r0 : %08lx\n", regs->ARM_r3, regs->ARM_r2, regs->ARM_r1, regs->ARM_r0); #ifdef <API key> /* * Overwrite SVC context which the error just occurs from regs * (tkHWANG) */ memcpy((void*)&<API key>, (void*)(regs), sizeof(<API key>)); #endif flags = regs->ARM_cpsr; buf[0] = flags & PSR_N_BIT ? 'N' : 'n'; buf[1] = flags & PSR_Z_BIT ? 'Z' : 'z'; buf[2] = flags & PSR_C_BIT ? 'C' : 'c'; buf[3] = flags & PSR_V_BIT ? 'V' : 'v'; buf[4] = '\0'; printk("Flags: %s IRQs o%s FIQs o%s Mode %s ISA %s Segment %s\n", buf, interrupts_enabled(regs) ? "n" : "ff", <API key>(regs) ? "n" : "ff", processor_modes[processor_mode(regs)], isa_modes[isa_mode(regs)], get_fs() == get_ds() ? "kernel" : "user"); #ifdef CONFIG_CPU_CP15 { unsigned int ctrl; buf[0] = '\0'; #ifdef CONFIG_CPU_CP15_MMU { unsigned int transbase, dac; asm("mrc p15, 0, %0, c2, c0\n\t" "mrc p15, 0, %1, c3, c0\n" : "=r" (transbase), "=r" (dac)); snprintf(buf, sizeof(buf), " Table: %08x DAC: %08x", transbase, dac); } #endif asm("mrc p15, 0, %0, c1, c0\n" : "=r" (ctrl)); printk("Control: %08x%s\n", ctrl, buf); } #endif <API key>(regs, 128); } void show_regs(struct pt_regs * regs) { printk("\n"); printk("Pid: %d, comm: %20s\n", task_pid_nr(current), current->comm); __show_regs(regs); __backtrace(); } <API key>(thread_notify_head); EXPORT_SYMBOL_GPL(thread_notify_head); /* * Free current thread data structures etc.. */ void exit_thread(void) { thread_notify(THREAD_NOTIFY_EXIT, current_thread_info()); } void flush_thread(void) { struct thread_info *thread = current_thread_info(); struct task_struct *tsk = current; memset(thread->used_cp, 0, sizeof(thread->used_cp)); memset(&tsk->thread.debug, 0, sizeof(struct debug_info)); memset(&thread->fpstate, 0, sizeof(union fp_state)); thread_notify(THREAD_NOTIFY_FLUSH, thread); } void release_thread(struct task_struct *dead_task) { } asmlinkage void ret_from_fork(void) __asm__("ret_from_fork"); int copy_thread(unsigned long clone_flags, unsigned long stack_start, unsigned long stk_sz, struct task_struct *p, struct pt_regs *regs) { struct thread_info *thread = task_thread_info(p); struct pt_regs *childregs = task_pt_regs(p); *childregs = *regs; childregs->ARM_r0 = 0; childregs->ARM_sp = stack_start; memset(&thread->cpu_context, 0, sizeof(struct cpu_context_save)); thread->cpu_context.sp = (unsigned long)childregs; thread->cpu_context.pc = (unsigned long)ret_from_fork; if (clone_flags & CLONE_SETTLS) thread->tp_value = regs->ARM_r3; return 0; } /* * Fill in the task's elfregs structure for a core dump. */ int dump_task_regs(struct task_struct *t, elf_gregset_t *elfregs) { elf_core_copy_regs(elfregs, task_pt_regs(t)); return 1; } /* * fill in the fpe structure for a core dump... */ int dump_fpu (struct pt_regs *regs, struct user_fp *fp) { struct thread_info *thread = current_thread_info(); int used_math = thread->used_cp[1] | thread->used_cp[2]; if (used_math) memcpy(fp, &thread->fpstate.soft, sizeof (*fp)); return used_math != 0; } EXPORT_SYMBOL(dump_fpu); /* * Shuffle the argument into the correct register before calling the * thread function. r4 is the thread argument, r5 is the pointer to * the thread function, and r6 points to the exit function. */ extern void <API key>(void); asm( ".pushsection .text\n" " .align\n" " .type <API key>, #function\n" "<API key>:\n" #ifdef <API key> " bl trace_hardirqs_on\n" #endif " msr cpsr_c, r7\n" " mov r0, r4\n" " mov lr, r6\n" " mov pc, r5\n" " .size <API key>, . - <API key>\n" " .popsection"); #ifdef CONFIG_ARM_UNWIND extern void kernel_thread_exit(long code); asm( ".pushsection .text\n" " .align\n" " .type kernel_thread_exit, #function\n" "kernel_thread_exit:\n" " .fnstart\n" " .cantunwind\n" " bl do_exit\n" " nop\n" " .fnend\n" " .size kernel_thread_exit, . - kernel_thread_exit\n" " .popsection"); #else #define kernel_thread_exit do_exit #endif /* * Create a kernel thread. */ pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags) { struct pt_regs regs; memset(&regs, 0, sizeof(regs)); regs.ARM_r4 = (unsigned long)arg; regs.ARM_r5 = (unsigned long)fn; regs.ARM_r6 = (unsigned long)kernel_thread_exit; regs.ARM_r7 = SVC_MODE | PSR_ENDSTATE | PSR_ISETSTATE; regs.ARM_pc = (unsigned long)<API key>; regs.ARM_cpsr = regs.ARM_r7 | PSR_I_BIT; return do_fork(flags|CLONE_VM|CLONE_UNTRACED, 0, &regs, 0, NULL, NULL); } EXPORT_SYMBOL(kernel_thread); unsigned long get_wchan(struct task_struct *p) { #ifdef FRAME_POINTER struct stackframe frame; int count = 0; if (!p || p == current || p->state == TASK_RUNNING) return 0; frame.fp = thread_saved_fp(p); frame.sp = thread_saved_sp(p); frame.lr = 0; /* recovered from the stack */ frame.pc = thread_saved_pc(p); do { int ret = unwind_frame(&frame); if (ret < 0) return 0; if (!in_sched_functions(frame.pc)) return frame.pc; } while (count ++ < 16); #endif return 0; }
#ifndef _LINUX_MM_H #define _LINUX_MM_H #include <linux/errno.h> #ifdef __KERNEL__ #include <linux/gfp.h> #include <linux/bug.h> #include <linux/list.h> #include <linux/mmzone.h> #include <linux/rbtree.h> #include <linux/atomic.h> #include <linux/debug_locks.h> #include <linux/mm_types.h> #include <linux/range.h> #include <linux/pfn.h> #include <linux/bit_spinlock.h> #include <linux/shrinker.h> struct mempolicy; struct anon_vma; struct anon_vma_chain; struct file_ra_state; struct user_struct; struct writeback_control; #ifndef CONFIG_DISCONTIGMEM /* Don't use mapnrs, do it properly */ extern unsigned long max_mapnr; #endif extern unsigned long num_physpages; extern unsigned long totalram_pages; extern void * high_memory; extern int page_cluster; #ifdef CONFIG_SYSCTL extern int <API key>; #else #define <API key> 0 #endif #include <asm/page.h> #include <asm/pgtable.h> #include <asm/processor.h> #define nth_page(page,n) pfn_to_page(page_to_pfn((page)) + (n)) /* to align the pointer to the (next) page boundary */ #define PAGE_ALIGN(addr) ALIGN(addr, PAGE_SIZE) /* * Linux kernel virtual memory manager primitives. * The idea being to have a "virtual" mm in the same way * we have a virtual fs - giving a cleaner interface to the * mm details, and allowing different kinds of memory mappings * (from shared memory to executable loading to arbitrary * mmap() functions). */ extern struct kmem_cache *vm_area_cachep; #ifndef CONFIG_MMU extern struct rb_root nommu_region_tree; extern struct rw_semaphore nommu_region_sem; extern unsigned int kobjsize(const void *objp); #endif /* * vm_flags in vm_area_struct, see mm_types.h. */ #define VM_NONE 0x00000000 #define VM_READ 0x00000001 /* currently active flags */ #define VM_WRITE 0x00000002 #define VM_EXEC 0x00000004 #define VM_SHARED 0x00000008 /* mprotect() hardcodes VM_MAYREAD >> 4 == VM_READ, and so for r/w/x bits. */ #define VM_MAYREAD 0x00000010 /* limits for mprotect() etc */ #define VM_MAYWRITE 0x00000020 #define VM_MAYEXEC 0x00000040 #define VM_MAYSHARE 0x00000080 #define VM_GROWSDOWN 0x00000100 /* general info on the segment */ #define VM_PFNMAP 0x00000400 /* Page-ranges managed without "struct page", just pure PFN */ #define VM_DENYWRITE 0x00000800 /* ETXTBSY on write attempts.. */ #define VM_LOCKED 0x00002000 #define VM_IO 0x00004000 /* Memory mapped I/O or similar */ /* Used by sys_madvise() */ #define VM_SEQ_READ 0x00008000 /* App will access data sequentially */ #define VM_RAND_READ 0x00010000 /* App will not benefit from clustered reads */ #define VM_DONTCOPY 0x00020000 /* Do not copy this vma on fork */ #define VM_DONTEXPAND 0x00040000 /* Cannot expand with mremap() */ #define VM_ACCOUNT 0x00100000 /* Is a VM accounted object */ #define VM_NORESERVE 0x00200000 /* should the VM suppress accounting */ #define VM_HUGETLB 0x00400000 /* Huge TLB Page VM */ #define VM_NONLINEAR 0x00800000 /* Is non-linear (remap_file_pages) */ #define VM_ARCH_1 0x01000000 /* <API key> flag */ #define VM_DONTDUMP 0x04000000 /* Do not include in the core dump */ #define VM_MIXEDMAP 0x10000000 /* Can contain "struct page" and pure PFN pages */ #define VM_HUGEPAGE 0x20000000 /* MADV_HUGEPAGE marked this vma */ #define VM_NOHUGEPAGE 0x40000000 /* MADV_NOHUGEPAGE marked this vma */ #define VM_MERGEABLE 0x80000000 /* KSM may merge identical pages */ #if defined(CONFIG_X86) # define VM_PAT VM_ARCH_1 /* PAT reserves whole VMA at once (x86) */ #elif defined(CONFIG_PPC) # define VM_SAO VM_ARCH_1 /* Strong Access Ordering (powerpc) */ #elif defined(CONFIG_PARISC) # define VM_GROWSUP VM_ARCH_1 #elif defined(CONFIG_IA64) # define VM_GROWSUP VM_ARCH_1 #elif !defined(CONFIG_MMU) # define VM_MAPPED_COPY VM_ARCH_1 /* T if mapped copy of data (nommu mmap) */ #endif #ifndef VM_GROWSUP # define VM_GROWSUP VM_NONE #endif /* Bits set in the VMA until the stack is in its final location */ #define <API key> (VM_RAND_READ | VM_SEQ_READ) #ifndef <API key> /* arch can override this */ #define <API key> <API key> #endif #ifdef <API key> #define VM_STACK_FLAGS (VM_GROWSUP | <API key> | VM_ACCOUNT) #else #define VM_STACK_FLAGS (VM_GROWSDOWN | <API key> | VM_ACCOUNT) #endif #define VM_READHINTMASK (VM_SEQ_READ | VM_RAND_READ) #define VM_ClearReadHint(v) (v)->vm_flags &= ~VM_READHINTMASK #define VM_NormalReadHint(v) (!((v)->vm_flags & VM_READHINTMASK)) #define <API key>(v) ((v)->vm_flags & VM_SEQ_READ) #define VM_RandomReadHint(v) ((v)->vm_flags & VM_RAND_READ) /* * Special vmas that are non-mergable, non-mlock()able. * Note: mm/huge_memory.c VM_NO_THP depends on this definition. */ #define VM_SPECIAL (VM_IO | VM_DONTEXPAND | VM_PFNMAP) /* * mapping from the currently active vm_flags protection bits (the * low four bits) to a page protection mask.. */ extern pgprot_t protection_map[16]; #define FAULT_FLAG_WRITE 0x01 /* Fault was a write access */ #define <API key> 0x02 /* Fault was via a nonlinear mapping */ #define FAULT_FLAG_MKWRITE 0x04 /* Fault was mkwrite of existing pte */ #define <API key> 0x08 /* Retry fault if blocking */ #define <API key> 0x10 /* Don't drop mmap_sem and wait when retrying */ #define FAULT_FLAG_KILLABLE 0x20 /* The fault task is in SIGKILL killable region */ #define FAULT_FLAG_TRIED 0x40 /* second try */ /* * vm_fault is filled by the the pagefault handler and passed to the vma's * ->fault function. The vma's ->fault is responsible for returning a bitmask * of VM_FAULT_xxx flags that give details about how the fault was handled. * * pgoff should be used in favour of virtual_address, if possible. If pgoff * is used, one may implement ->remap_pages to get nonlinear mapping support. */ struct vm_fault { unsigned int flags; /* FAULT_FLAG_xxx flags */ pgoff_t pgoff; /* Logical page offset based on vma */ void __user *virtual_address; /* Faulting virtual address */ struct page *page; /* ->fault handlers should return a * page here, unless VM_FAULT_NOPAGE * is set (which is also implied by * VM_FAULT_ERROR). */ }; /* * These are the virtual MM functions - opening of an area, closing and * unmapping it (needed to keep files on disk up-to-date etc), pointer * to the functions called when a no-page or a wp-page exception occurs. */ struct <API key> { void (*open)(struct vm_area_struct * area); void (*close)(struct vm_area_struct * area); int (*fault)(struct vm_area_struct *vma, struct vm_fault *vmf); /* notification that a previously read-only page is about to become * writable, if an error is returned it will cause a SIGBUS */ int (*page_mkwrite)(struct vm_area_struct *vma, struct vm_fault *vmf); /* called by access_process_vm when get_user_pages() fails, typically * for use by special VMAs that can switch between memory and hardware */ int (*access)(struct vm_area_struct *vma, unsigned long addr, void *buf, int len, int write); #ifdef CONFIG_NUMA /* * set_policy() op must add a reference to any non-NULL @new mempolicy * to hold the policy upon return. Caller should pass NULL @new to * remove a policy and fall back to surrounding context--i.e. do not * install a MPOL_DEFAULT policy, nor the task or system default * mempolicy. */ int (*set_policy)(struct vm_area_struct *vma, struct mempolicy *new); /* * get_policy() op must add reference [mpol_get()] to any policy at * (vma,addr) marked as MPOL_SHARED. The shared policy infrastructure * in mm/mempolicy.c will do this automatically. * get_policy() must NOT add a ref if the policy at (vma,addr) is not * marked as MPOL_SHARED. vma policies are protected by the mmap_sem. * If no [shared/vma] mempolicy exists at the addr, get_policy() op * must return NULL--i.e., do not "fallback" to task or system default * policy. */ struct mempolicy *(*get_policy)(struct vm_area_struct *vma, unsigned long addr); int (*migrate)(struct vm_area_struct *vma, const nodemask_t *from, const nodemask_t *to, unsigned long flags); #endif /* called by <API key>() to populate non-linear mapping */ int (*remap_pages)(struct vm_area_struct *vma, unsigned long addr, unsigned long size, pgoff_t pgoff); }; struct mmu_gather; struct inode; #define page_private(page) ((page)->private) #define set_page_private(page, v) ((page)->private = (v)) /* It's valid only if the page is free path or free_list */ static inline void <API key>(struct page *page, int migratetype) { page->index = migratetype; } /* It's valid only if the page is free path or free_list */ static inline int <API key>(struct page *page) { return page->index; } /* * FIXME: take this include out, include page-flags.h in * files which need it (119 of them) */ #include <linux/page-flags.h> #include <linux/huge_mm.h> /* * Methods to modify the page usage count. * * What counts for a page usage: * - cache mapping (page->mapping) * - private data (page->private) * - page mapped in a task's page tables, each mapping * is counted separately * * Also, many kernel routines increase the page count before a critical * routine so they can be sure the page doesn't go away from under them. */ /* * Drop a ref, return true if the refcount fell to zero (the page has no users) */ static inline int put_page_testzero(struct page *page) { VM_BUG_ON(atomic_read(&page->_count) == 0); return atomic_dec_and_test(&page->_count); } /* * Try to grab a ref unless the page has a refcount of zero, return false if * that is the case. */ static inline int <API key>(struct page *page) { return atomic_inc_not_zero(&page->_count); } extern int page_is_ram(unsigned long pfn); /* Support for virtually mapped pages */ struct page *vmalloc_to_page(const void *addr); unsigned long vmalloc_to_pfn(const void *addr); /* * Determine if an address is within the vmalloc range * * On nommu, vmalloc/vfree wrap through kmalloc/kfree directly, so there * is no special casing required. */ static inline int is_vmalloc_addr(const void *x) { #ifdef CONFIG_MMU unsigned long addr = (unsigned long)x; return addr >= VMALLOC_START && addr < VMALLOC_END; #else return 0; #endif } #ifdef CONFIG_MMU extern int <API key>(const void *x); #else static inline int <API key>(const void *x) { return 0; } #endif static inline void compound_lock(struct page *page) { #ifdef <API key> VM_BUG_ON(PageSlab(page)); bit_spin_lock(PG_compound_lock, &page->flags); #endif } static inline void compound_unlock(struct page *page) { #ifdef <API key> VM_BUG_ON(PageSlab(page)); bit_spin_unlock(PG_compound_lock, &page->flags); #endif } static inline unsigned long <API key>(struct page *page) { unsigned long uninitialized_var(flags); #ifdef <API key> local_irq_save(flags); compound_lock(page); #endif return flags; } static inline void <API key>(struct page *page, unsigned long flags) { #ifdef <API key> compound_unlock(page); local_irq_restore(flags); #endif } static inline struct page *compound_head(struct page *page) { if (unlikely(PageTail(page))) return page->first_page; return page; } /* * The atomic page->_mapcount, starts from -1: so that transitions * both from it and to it can be tracked, using atomic_inc_and_test * and atomic_add_negative(-1). */ static inline void reset_page_mapcount(struct page *page) { atomic_set(&(page)->_mapcount, -1); } static inline int page_mapcount(struct page *page) { return atomic_read(&(page)->_mapcount) + 1; } static inline int page_count(struct page *page) { return atomic_read(&compound_head(page)->_count); } static inline void get_huge_page_tail(struct page *page) { /* * <API key>() cannot run * from under us. */ VM_BUG_ON(page_mapcount(page) < 0); VM_BUG_ON(atomic_read(&page->_count) != 0); atomic_inc(&page->_mapcount); } extern bool __get_page_tail(struct page *page); static inline void get_page(struct page *page) { if (unlikely(PageTail(page))) if (likely(__get_page_tail(page))) return; /* * Getting a normal page or the head of a compound page * requires to already have an elevated page->_count. */ VM_BUG_ON(atomic_read(&page->_count) <= 0); atomic_inc(&page->_count); } static inline struct page *virt_to_head_page(const void *x) { struct page *page = virt_to_page(x); return compound_head(page); } /* * Setup the page count before being freed into the page allocator for * the first time (boot or memory hotplug) */ static inline void init_page_count(struct page *page) { atomic_set(&page->_count, 1); } /* * PageBuddy() indicate that the page is free and in the buddy system * (see mm/page_alloc.c). * * <API key> must be <= -2 but better not too close to * -2 so that an underflow of the page_mapcount() won't be mistaken * for a genuine <API key>. -128 can be created very * efficiently by most CPU architectures. */ #define <API key> (-128) static inline int PageBuddy(struct page *page) { return atomic_read(&page->_mapcount) == <API key>; } static inline void __SetPageBuddy(struct page *page) { VM_BUG_ON(atomic_read(&page->_mapcount) != -1); atomic_set(&page->_mapcount, <API key>); } static inline void __ClearPageBuddy(struct page *page) { VM_BUG_ON(!PageBuddy(page)); atomic_set(&page->_mapcount, -1); } void put_page(struct page *page); void put_pages_list(struct list_head *pages); void split_page(struct page *page, unsigned int order); int split_free_page(struct page *page); int capture_free_page(struct page *page, int alloc_order, int migratetype); /* * Compound pages have a destructor function. Provide a * prototype for that function and accessor functions. * These are _only_ valid on the head of a PG_compound page. */ typedef void compound_page_dtor(struct page *); static inline void <API key>(struct page *page, compound_page_dtor *dtor) { page[1].lru.next = (void *)dtor; } static inline compound_page_dtor *<API key>(struct page *page) { return (compound_page_dtor *)page[1].lru.next; } static inline int compound_order(struct page *page) { if (!PageHead(page)) return 0; return (unsigned long)page[1].lru.prev; } static inline int <API key>(struct page *page) { int order; unsigned long flags; if (!PageHead(page)) return 0; flags = <API key>(page); order = compound_order(page); <API key>(page, flags); return order; } static inline void set_compound_order(struct page *page, unsigned long order) { page[1].lru.prev = (void *)order; } #ifdef CONFIG_MMU /* * Do pte_mkwrite, but only if the vma says VM_WRITE. We do this when * servicing faults for write access. In the normal case, do always want * pte_mkwrite. But get_user_pages can cause write faults for mappings * that do not have writing enabled, when used by access_process_vm. */ static inline pte_t maybe_mkwrite(pte_t pte, struct vm_area_struct *vma) { if (likely(vma->vm_flags & VM_WRITE)) pte = pte_mkwrite(pte); return pte; } #endif /* * Multiple processes may "see" the same page. E.g. for untouched * mappings of /dev/null, all processes see the same page full of * zeroes, and text pages of executables and shared libraries have * only one copy in memory, at most, normally. * * For the non-reserved pages, page_count(page) denotes a reference count. * page_count() == 0 means the page is free. page->lru is then used for * freelist management in the buddy allocator. * page_count() > 0 means the page has been allocated. * * Pages are allocated by the slab allocator in order to provide memory * to kmalloc and kmem_cache_alloc. In this case, the management of the * page, and the fields in 'struct page' are the responsibility of mm/slab.c * unless a particular usage is carefully commented. (the responsibility of * freeing the kmalloc memory is the caller's, of course). * * A page may be used by anyone else who does a __get_free_page(). * In this case, page_count still tracks the references, and should only * be used through the normal accessor functions. The top bits of page->flags * and page->virtual store page management information, but all other fields * are unused and could be used privately, carefully. The management of this * page is the responsibility of the one who allocated it, and those who have * subsequently been given references to it. * * The other pages (we may call them "pagecache pages") are completely * managed by the Linux memory manager: I/O, buffers, swapping etc. * The following discussion applies only to them. * * A pagecache page contains an opaque `private' member, which belongs to the * page's address_space. Usually, this is the address of a circular list of * the page's disk buffers. PG_private must be set to tell the VM to call * into the filesystem to release these pages. * * A page may belong to an inode's memory mapping. In this case, page->mapping * is the pointer to the inode, and page->index is the file offset of the page, * in units of PAGE_CACHE_SIZE. * * If pagecache pages are not associated with an inode, they are said to be * anonymous pages. These may become associated with the swapcache, and in that * case PG_swapcache is set, and page->private is an offset into the swapcache. * * In either case (swapcache or inode backed), the pagecache itself holds one * reference to the page. Setting PG_private should also increment the * refcount. The each user mapping also has a reference to the page. * * The pagecache pages are stored in a per-mapping radix tree, which is * rooted at mapping->page_tree, and indexed by offset. * Where 2.4 and early 2.6 kernels kept dirty/clean pages in per-address_space * lists, we instead now tag pages as dirty/writeback in the radix tree. * * All pagecache pages may be subject to I/O: * - inode pages may need to be read from disk, * - inode pages which have been modified and are MAP_SHARED may need * to be written back to the inode on disk, * - anonymous pages (including MAP_PRIVATE file mappings) which have been * modified may need to be swapped out to swap space and (later) to be read * back into memory. */ /* * The zone field is never updated after free_area_init_core() * sets it, so none of the operations on it need to be atomic. */ /* * page->flags layout: * * There are three possibilities for how page->flags get * laid out. The first is for the normal case, without * sparsemem. The second is for sparsemem when there is * plenty of space for node and section. The last is when * we have run out of space and have to fall back to an * alternate (slower) way of determining the node. * * No sparsemem or sparsemem vmemmap: | NODE | ZONE | ... | FLAGS | * classic sparse with space for node:| SECTION | NODE | ZONE | ... | FLAGS | * classic sparse no space for node: | SECTION | ZONE | ... | FLAGS | */ #if defined(CONFIG_SPARSEMEM) && !defined(<API key>) #define SECTIONS_WIDTH SECTIONS_SHIFT #else #define SECTIONS_WIDTH 0 #endif #define ZONES_WIDTH ZONES_SHIFT #if SECTIONS_WIDTH+ZONES_WIDTH+NODES_SHIFT <= BITS_PER_LONG - NR_PAGEFLAGS #define NODES_WIDTH NODES_SHIFT #else #ifdef <API key> #error "Vmemmap: No space for nodes field in page flags" #endif #define NODES_WIDTH 0 #endif /* Page flags: | [SECTION] | [NODE] | ZONE | ... | FLAGS | */ #define SECTIONS_PGOFF ((sizeof(unsigned long)*8) - SECTIONS_WIDTH) #define NODES_PGOFF (SECTIONS_PGOFF - NODES_WIDTH) #define ZONES_PGOFF (NODES_PGOFF - ZONES_WIDTH) /* * We are going to use the flags for the page to node mapping if its in * there. This includes the case where there is no node, so it is implicit. */ #if !(NODES_WIDTH > 0 || NODES_SHIFT == 0) #define <API key> #endif /* * Define the bit shifts to access each section. For non-existent * sections we define the shift as 0; that plus a 0 mask ensures * the compiler will optimise away reference to them. */ #define SECTIONS_PGSHIFT (SECTIONS_PGOFF * (SECTIONS_WIDTH != 0)) #define NODES_PGSHIFT (NODES_PGOFF * (NODES_WIDTH != 0)) #define ZONES_PGSHIFT (ZONES_PGOFF * (ZONES_WIDTH != 0)) /* NODE:ZONE or SECTION:ZONE is used to ID a zone for the buddy allocator */ #ifdef <API key> #define ZONEID_SHIFT (SECTIONS_SHIFT + ZONES_SHIFT) #define ZONEID_PGOFF ((SECTIONS_PGOFF < ZONES_PGOFF)? \ SECTIONS_PGOFF : ZONES_PGOFF) #else #define ZONEID_SHIFT (NODES_SHIFT + ZONES_SHIFT) #define ZONEID_PGOFF ((NODES_PGOFF < ZONES_PGOFF)? \ NODES_PGOFF : ZONES_PGOFF) #endif #define ZONEID_PGSHIFT (ZONEID_PGOFF * (ZONEID_SHIFT != 0)) #if SECTIONS_WIDTH+NODES_WIDTH+ZONES_WIDTH > BITS_PER_LONG - NR_PAGEFLAGS #error SECTIONS_WIDTH+NODES_WIDTH+ZONES_WIDTH > BITS_PER_LONG - NR_PAGEFLAGS #endif #define ZONES_MASK ((1UL << ZONES_WIDTH) - 1) #define NODES_MASK ((1UL << NODES_WIDTH) - 1) #define SECTIONS_MASK ((1UL << SECTIONS_WIDTH) - 1) #define ZONEID_MASK ((1UL << ZONEID_SHIFT) - 1) static inline enum zone_type page_zonenum(const struct page *page) { return (page->flags >> ZONES_PGSHIFT) & ZONES_MASK; } /* * The identification function is only used by the buddy allocator for * determining if two pages could be buddies. We are not really * identifying a zone since we could be using a the section number * id if we have not node id available in page flags. * We guarantee only that it will return the same value for two * combinable pages in a zone. */ static inline int page_zone_id(struct page *page) { return (page->flags >> ZONEID_PGSHIFT) & ZONEID_MASK; } static inline int zone_to_nid(struct zone *zone) { #ifdef CONFIG_NUMA return zone->node; #else return 0; #endif } #ifdef <API key> extern int page_to_nid(const struct page *page); #else static inline int page_to_nid(const struct page *page) { return (page->flags >> NODES_PGSHIFT) & NODES_MASK; } #endif static inline struct zone *page_zone(const struct page *page) { return &NODE_DATA(page_to_nid(page))->node_zones[page_zonenum(page)]; } #if defined(CONFIG_SPARSEMEM) && !defined(<API key>) static inline void set_page_section(struct page *page, unsigned long section) { page->flags &= ~(SECTIONS_MASK << SECTIONS_PGSHIFT); page->flags |= (section & SECTIONS_MASK) << SECTIONS_PGSHIFT; } static inline unsigned long page_to_section(const struct page *page) { return (page->flags >> SECTIONS_PGSHIFT) & SECTIONS_MASK; } #endif static inline void set_page_zone(struct page *page, enum zone_type zone) { page->flags &= ~(ZONES_MASK << ZONES_PGSHIFT); page->flags |= (zone & ZONES_MASK) << ZONES_PGSHIFT; } static inline void set_page_node(struct page *page, unsigned long node) { page->flags &= ~(NODES_MASK << NODES_PGSHIFT); page->flags |= (node & NODES_MASK) << NODES_PGSHIFT; } static inline void set_page_links(struct page *page, enum zone_type zone, unsigned long node, unsigned long pfn) { set_page_zone(page, zone); set_page_node(page, node); #if defined(CONFIG_SPARSEMEM) && !defined(<API key>) set_page_section(page, pfn_to_section_nr(pfn)); #endif } /* * Some inline functions in vmstat.h depend on page_zone() */ #include <linux/vmstat.h> static __always_inline void *lowmem_page_address(const struct page *page) { return __va(PFN_PHYS(page_to_pfn(page))); } #if defined(CONFIG_HIGHMEM) && !defined(WANT_PAGE_VIRTUAL) #define HASHED_PAGE_VIRTUAL #endif #if defined(WANT_PAGE_VIRTUAL) #define page_address(page) ((page)->virtual) #define set_page_address(page, address) \ do { \ (page)->virtual = (address); \ } while(0) #define page_address_init() do { } while(0) #endif #if defined(HASHED_PAGE_VIRTUAL) void *page_address(const struct page *page); void set_page_address(struct page *page, void *virtual); void page_address_init(void); #endif #if !defined(HASHED_PAGE_VIRTUAL) && !defined(WANT_PAGE_VIRTUAL) #define page_address(page) lowmem_page_address(page) #define set_page_address(page, address) do { } while(0) #define page_address_init() do { } while(0) #endif /* * On an anonymous page mapped into a user virtual memory area, * page->mapping points to its anon_vma, not to a struct address_space; * with the PAGE_MAPPING_ANON bit set to distinguish it. See rmap.h. * * On an anonymous page in a VM_MERGEABLE area, if CONFIG_KSM is enabled, * the PAGE_MAPPING_KSM bit may be set along with the PAGE_MAPPING_ANON bit; * and then page->mapping points, not to an anon_vma, but to a private * structure which KSM associates with that merged page. See ksm.h. * * PAGE_MAPPING_KSM without PAGE_MAPPING_ANON is currently never used. * * Please note that, confusingly, "page_mapping" refers to the inode * address_space which maps the page from disk; whereas "page_mapped" * refers to user virtual address space into which the page is mapped. */ #define PAGE_MAPPING_ANON 1 #define PAGE_MAPPING_KSM 2 #define PAGE_MAPPING_FLAGS (PAGE_MAPPING_ANON | PAGE_MAPPING_KSM) extern struct address_space swapper_space; static inline struct address_space *page_mapping(struct page *page) { struct address_space *mapping = page->mapping; VM_BUG_ON(PageSlab(page)); if (unlikely(PageSwapCache(page))) mapping = &swapper_space; else if ((unsigned long)mapping & PAGE_MAPPING_ANON) mapping = NULL; return mapping; } /* Neutral page->mapping pointer to address_space or anon_vma or other */ static inline void *page_rmapping(struct page *page) { return (void *)((unsigned long)page->mapping & ~PAGE_MAPPING_FLAGS); } extern struct address_space *__page_file_mapping(struct page *); static inline struct address_space *page_file_mapping(struct page *page) { if (unlikely(PageSwapCache(page))) return __page_file_mapping(page); return page->mapping; } static inline int PageAnon(struct page *page) { return ((unsigned long)page->mapping & PAGE_MAPPING_ANON) != 0; } /* * Return the pagecache index of the passed page. Regular pagecache pages * use ->index whereas swapcache pages use ->private */ static inline pgoff_t page_index(struct page *page) { if (unlikely(PageSwapCache(page))) return page_private(page); return page->index; } extern pgoff_t __page_file_index(struct page *page); /* * Return the file index of the page. Regular pagecache pages use ->index * whereas swapcache pages use swp_offset(->private) */ static inline pgoff_t page_file_index(struct page *page) { if (unlikely(PageSwapCache(page))) return __page_file_index(page); return page->index; } /* * Return true if this page is mapped into pagetables. */ static inline int page_mapped(struct page *page) { return atomic_read(&(page)->_mapcount) >= 0; } /* * Different kinds of faults, as returned by handle_mm_fault(). * Used to decide whether a process gets delivered SIGBUS or * just gets major/minor fault counters bumped up. */ #define VM_FAULT_MINOR 0 /* For backwards compat. Remove me quickly. */ #define VM_FAULT_OOM 0x0001 #define VM_FAULT_SIGBUS 0x0002 #define VM_FAULT_MAJOR 0x0004 #define VM_FAULT_WRITE 0x0008 /* Special case for get_user_pages */ #define VM_FAULT_HWPOISON 0x0010 /* Hit poisoned small page */ #define <API key> 0x0020 /* Hit poisoned large page. Index encoded in upper bits */ #define VM_FAULT_NOPAGE 0x0100 /* ->fault installed the pte, not return page */ #define VM_FAULT_LOCKED 0x0200 /* ->fault locked the returned page */ #define VM_FAULT_RETRY 0x0400 /* ->fault blocked, must retry */ #ifdef CONFIG_WING #define VM_FAULT_SYNC 0x0800 #endif #define <API key> 0xf000 /* encodes hpage index for large hwpoison */ #define VM_FAULT_ERROR (VM_FAULT_OOM | VM_FAULT_SIGBUS | VM_FAULT_HWPOISON | \ <API key>) /* Encode hstate index for a hwpoisoned large page */ #define VM_FAULT_SET_HINDEX(x) ((x) << 12) #define VM_FAULT_GET_HINDEX(x) (((x) >> 12) & 0xf) /* * Can be called by the pagefault handler when it gets a VM_FAULT_OOM. */ extern void <API key>(void); #define offset_in_page(p) ((unsigned long)(p) & ~PAGE_MASK) /* * Flags passed to show_mem() and show_free_areas() to suppress output in * various contexts. */ #define <API key> (0x0001u) /* filter disallowed nodes */ extern void show_free_areas(unsigned int flags); extern bool <API key>(unsigned int flags, int nid); int shmem_zero_setup(struct vm_area_struct *); extern int can_do_mlock(void); extern int user_shm_lock(size_t, struct user_struct *); extern void user_shm_unlock(size_t, struct user_struct *); /* * Parameter block passed down to zap_pte_range in exceptional cases. */ struct zap_details { struct vm_area_struct *nonlinear_vma; /* Check page->index if set */ struct address_space *check_mapping; /* Check page->mapping if set */ pgoff_t first_index; /* Lowest page->index to unmap */ pgoff_t last_index; /* Highest page->index to unmap */ }; struct page *vm_normal_page(struct vm_area_struct *vma, unsigned long addr, pte_t pte); int zap_vma_ptes(struct vm_area_struct *vma, unsigned long address, unsigned long size); void zap_page_range(struct vm_area_struct *vma, unsigned long address, unsigned long size, struct zap_details *); void unmap_vmas(struct mmu_gather *tlb, struct vm_area_struct *start_vma, unsigned long start, unsigned long end); /** * mm_walk - callbacks for walk_page_range * @pgd_entry: if set, called for each non-empty PGD (top-level) entry * @pud_entry: if set, called for each non-empty PUD (2nd-level) entry * @pmd_entry: if set, called for each non-empty PMD (3rd-level) entry * this handler is required to be able to handle * pmd_trans_huge() pmds. They may simply choose to * split_huge_page() instead of handling it explicitly. * @pte_entry: if set, called for each non-empty PTE (4th-level) entry * @pte_hole: if set, called for each hole at all levels * @hugetlb_entry: if set, called for each hugetlb entry * *Caution*: The caller must hold mmap_sem() if @hugetlb_entry * is used. * * (see walk_page_range for more details) */ struct mm_walk { int (*pgd_entry)(pgd_t *, unsigned long, unsigned long, struct mm_walk *); int (*pud_entry)(pud_t *, unsigned long, unsigned long, struct mm_walk *); int (*pmd_entry)(pmd_t *, unsigned long, unsigned long, struct mm_walk *); int (*pte_entry)(pte_t *, unsigned long, unsigned long, struct mm_walk *); int (*pte_hole)(unsigned long, unsigned long, struct mm_walk *); int (*hugetlb_entry)(pte_t *, unsigned long, unsigned long, unsigned long, struct mm_walk *); struct mm_struct *mm; void *private; }; int walk_page_range(unsigned long addr, unsigned long end, struct mm_walk *walk); void free_pgd_range(struct mmu_gather *tlb, unsigned long addr, unsigned long end, unsigned long floor, unsigned long ceiling); int copy_page_range(struct mm_struct *dst, struct mm_struct *src, struct vm_area_struct *vma); void unmap_mapping_range(struct address_space *mapping, loff_t const holebegin, loff_t const holelen, int even_cows); int follow_pfn(struct vm_area_struct *vma, unsigned long address, unsigned long *pfn); int follow_phys(struct vm_area_struct *vma, unsigned long address, unsigned int flags, unsigned long *prot, resource_size_t *phys); int generic_access_phys(struct vm_area_struct *vma, unsigned long addr, void *buf, int len, int write); static inline void <API key>(struct address_space *mapping, loff_t const holebegin, loff_t const holelen) { unmap_mapping_range(mapping, holebegin, holelen, 0); } extern void truncate_pagecache(struct inode *inode, loff_t old, loff_t new); extern void truncate_setsize(struct inode *inode, loff_t newsize); extern int vmtruncate(struct inode *inode, loff_t offset); void <API key>(struct inode *inode, loff_t offset, loff_t end); int truncate_inode_page(struct address_space *mapping, struct page *page); int <API key>(struct address_space *mapping, struct page *page); int <API key>(struct page *page); #ifdef CONFIG_MMU extern int handle_mm_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, unsigned int flags); extern int fixup_user_fault(struct task_struct *tsk, struct mm_struct *mm, unsigned long address, unsigned int fault_flags); #else static inline int handle_mm_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, unsigned int flags) { /* should never happen if there's no MMU */ BUG(); return VM_FAULT_SIGBUS; } static inline int fixup_user_fault(struct task_struct *tsk, struct mm_struct *mm, unsigned long address, unsigned int fault_flags) { /* should never happen if there's no MMU */ BUG(); return -EFAULT; } #endif extern int make_pages_present(unsigned long addr, unsigned long end); extern int access_process_vm(struct task_struct *tsk, unsigned long addr, void *buf, int len, int write); extern int access_remote_vm(struct mm_struct *mm, unsigned long addr, void *buf, int len, int write); int __get_user_pages(struct task_struct *tsk, struct mm_struct *mm, unsigned long start, int len, unsigned int foll_flags, struct page **pages, struct vm_area_struct **vmas, int *nonblocking); int get_user_pages(struct task_struct *tsk, struct mm_struct *mm, unsigned long start, int nr_pages, int write, int force, struct page **pages, struct vm_area_struct **vmas); int get_user_pages_fast(unsigned long start, int nr_pages, int write, struct page **pages); struct kvec; int get_kernel_pages(const struct kvec *iov, int nr_pages, int write, struct page **pages); int get_kernel_page(unsigned long start, int write, struct page **pages); struct page *get_dump_page(unsigned long addr); extern int try_to_release_page(struct page * page, gfp_t gfp_mask); extern void do_invalidatepage(struct page *page, unsigned long offset); int <API key>(struct page *page); int <API key>(struct page *page); int <API key>(struct writeback_control *wbc, struct page *page); void <API key>(struct page *page, struct address_space *mapping); void <API key>(struct page *page); int set_page_dirty(struct page *page); int set_page_dirty_lock(struct page *page); int <API key>(struct page *page); /* Is the vma a continuation of the stack vma above it? */ static inline int vma_growsdown(struct vm_area_struct *vma, unsigned long addr) { return vma && (vma->vm_end == addr) && (vma->vm_flags & VM_GROWSDOWN); } static inline int <API key>(struct vm_area_struct *vma, unsigned long addr) { return (vma->vm_flags & VM_GROWSDOWN) && (vma->vm_start == addr) && !vma_growsdown(vma->vm_prev, addr); } /* Is the vma a continuation of the stack vma below it? */ static inline int vma_growsup(struct vm_area_struct *vma, unsigned long addr) { return vma && (vma->vm_start == addr) && (vma->vm_flags & VM_GROWSUP); } static inline int <API key>(struct vm_area_struct *vma, unsigned long addr) { return (vma->vm_flags & VM_GROWSUP) && (vma->vm_end == addr) && !vma_growsup(vma->vm_next, addr); } extern pid_t vm_is_stack(struct task_struct *task, struct vm_area_struct *vma, int in_group); extern unsigned long move_page_tables(struct vm_area_struct *vma, unsigned long old_addr, struct vm_area_struct *new_vma, unsigned long new_addr, unsigned long len, bool need_rmap_locks); extern unsigned long do_mremap(unsigned long addr, unsigned long old_len, unsigned long new_len, unsigned long flags, unsigned long new_addr); extern int mprotect_fixup(struct vm_area_struct *vma, struct vm_area_struct **pprev, unsigned long start, unsigned long end, unsigned long newflags); /* * doesn't attempt to fault and will return short. */ int <API key>(unsigned long start, int nr_pages, int write, struct page **pages); /* * per-process(per-mm_struct) statistics. */ static inline unsigned long get_mm_counter(struct mm_struct *mm, int member) { long val = atomic_long_read(&mm->rss_stat.count[member]); #ifdef SPLIT_RSS_COUNTING /* * counter is updated in asynchronous manner and may go to minus. * But it's never be expected number for users. */ if (val < 0) val = 0; #endif return (unsigned long)val; } static inline void add_mm_counter(struct mm_struct *mm, int member, long value) { atomic_long_add(value, &mm->rss_stat.count[member]); } static inline void inc_mm_counter(struct mm_struct *mm, int member) { atomic_long_inc(&mm->rss_stat.count[member]); } static inline void dec_mm_counter(struct mm_struct *mm, int member) { atomic_long_dec(&mm->rss_stat.count[member]); } static inline unsigned long get_mm_rss(struct mm_struct *mm) { return get_mm_counter(mm, MM_FILEPAGES) + get_mm_counter(mm, MM_ANONPAGES); } static inline unsigned long get_mm_hiwater_rss(struct mm_struct *mm) { return max(mm->hiwater_rss, get_mm_rss(mm)); } static inline unsigned long get_mm_hiwater_vm(struct mm_struct *mm) { return max(mm->hiwater_vm, mm->total_vm); } static inline void update_hiwater_rss(struct mm_struct *mm) { unsigned long _rss = get_mm_rss(mm); if ((mm)->hiwater_rss < _rss) (mm)->hiwater_rss = _rss; } static inline void update_hiwater_vm(struct mm_struct *mm) { if (mm->hiwater_vm < mm->total_vm) mm->hiwater_vm = mm->total_vm; } static inline void <API key>(unsigned long *maxrss, struct mm_struct *mm) { unsigned long hiwater_rss = get_mm_hiwater_rss(mm); if (*maxrss < hiwater_rss) *maxrss = hiwater_rss; } #if defined(SPLIT_RSS_COUNTING) void sync_mm_rss(struct mm_struct *mm); #else static inline void sync_mm_rss(struct mm_struct *mm) { } #endif int <API key>(struct vm_area_struct *vma); extern pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr, spinlock_t **ptl); static inline pte_t *get_locked_pte(struct mm_struct *mm, unsigned long addr, spinlock_t **ptl) { pte_t *ptep; __cond_lock(*ptl, ptep = __get_locked_pte(mm, addr, ptl)); return ptep; } #ifdef <API key> static inline int __pud_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address) { return 0; } #else int __pud_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address); #endif #ifdef <API key> static inline int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address) { return 0; } #else int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address); #endif int __pte_alloc(struct mm_struct *mm, struct vm_area_struct *vma, pmd_t *pmd, unsigned long address); int __pte_alloc_kernel(pmd_t *pmd, unsigned long address); /* * The following ifdef needed to get the 4level-fixup.h header to work. * Remove it when 4level-fixup.h has been removed. */ #if defined(CONFIG_MMU) && !defined(<API key>) static inline pud_t *pud_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address) { return (unlikely(pgd_none(*pgd)) && __pud_alloc(mm, pgd, address))? NULL: pud_offset(pgd, address); } static inline pmd_t *pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address) { return (unlikely(pud_none(*pud)) && __pmd_alloc(mm, pud, address))? NULL: pmd_offset(pud, address); } #endif /* CONFIG_MMU && !<API key> */ #if USE_SPLIT_PTLOCKS /* * We tuck a spinlock to guard each pagetable page into its struct page, * at page->private, with BUILD_BUG_ON to make sure that this will not * overflow into the next struct page (as it might with DEBUG_SPINLOCK). * When freeing, reset page->mapping so free_pages_check won't complain. */ #define __pte_lockptr(page) &((page)->ptl) #define pte_lock_init(_page) do { \ spin_lock_init(__pte_lockptr(_page)); \ } while (0) #define pte_lock_deinit(page) ((page)->mapping = NULL) #define pte_lockptr(mm, pmd) ({(void)(mm); __pte_lockptr(pmd_page(*(pmd)));}) #else /* !USE_SPLIT_PTLOCKS */ /* * We use mm->page_table_lock to guard all pagetable pages of the mm. */ #define pte_lock_init(page) do {} while (0) #define pte_lock_deinit(page) do {} while (0) #define pte_lockptr(mm, pmd) ({(void)(pmd); &(mm)->page_table_lock;}) #endif /* USE_SPLIT_PTLOCKS */ static inline void pgtable_page_ctor(struct page *page) { pte_lock_init(page); inc_zone_page_state(page, NR_PAGETABLE); } static inline void pgtable_page_dtor(struct page *page) { pte_lock_deinit(page); dec_zone_page_state(page, NR_PAGETABLE); } #define pte_offset_map_lock(mm, pmd, address, ptlp) \ ({ \ spinlock_t *__ptl = pte_lockptr(mm, pmd); \ pte_t *__pte = pte_offset_map(pmd, address); \ *(ptlp) = __ptl; \ spin_lock(__ptl); \ __pte; \ }) #define pte_unmap_unlock(pte, ptl) do { \ spin_unlock(ptl); \ pte_unmap(pte); \ } while (0) #define pte_alloc_map(mm, vma, pmd, address) \ ((unlikely(pmd_none(*(pmd))) && __pte_alloc(mm, vma, \ pmd, address))? \ NULL: pte_offset_map(pmd, address)) #define pte_alloc_map_lock(mm, pmd, address, ptlp) \ ((unlikely(pmd_none(*(pmd))) && __pte_alloc(mm, NULL, \ pmd, address))? \ NULL: pte_offset_map_lock(mm, pmd, address, ptlp)) #define pte_alloc_kernel(pmd, address) \ ((unlikely(pmd_none(*(pmd))) && __pte_alloc_kernel(pmd, address))? \ NULL: pte_offset_kernel(pmd, address)) extern void free_area_init(unsigned long * zones_size); extern void free_area_init_node(int nid, unsigned long * zones_size, unsigned long zone_start_pfn, unsigned long *zholes_size); extern void free_initmem(void); #ifdef <API key> /* * With <API key> set, an architecture may initialise its * zones, allocate the backing mem_map and account for memory holes in a more * architecture independent manner. This is a substitute for creating the * zone_sizes[] and zholes_size[] arrays and passing them to * free_area_init_node() * * An architecture is expected to register range of page frames backed by * physical memory with memblock_add[_node]() before calling * <API key>() passing in the PFN each zone ends at. At a basic * usage, an architecture is expected to do something like * * unsigned long max_zone_pfns[MAX_NR_ZONES] = {max_dma, max_normal_pfn, * max_highmem_pfn}; * <API key>() * memblock_add_node(base, size, nid) * <API key>(max_zone_pfns); * * <API key>() calls free_bootmem_node() for each * registered physical page range. Similarly * <API key>() calls memory_present() for * each range when SPARSEMEM is enabled. * * See mm/page_alloc.c for more information on each function exposed by * <API key>. */ extern void <API key>(unsigned long *max_zone_pfn); unsigned long <API key>(void); unsigned long <API key>(int nid, unsigned long start_pfn, unsigned long end_pfn); extern unsigned long <API key>(unsigned long start_pfn, unsigned long end_pfn); extern void <API key>(unsigned int nid, unsigned long *start_pfn, unsigned long *end_pfn); extern unsigned long <API key>(void); extern void <API key>(int nid, unsigned long max_low_pfn); extern void <API key>(int nid); #endif /* <API key> */ #if !defined(<API key>) && \ !defined(<API key>) static inline int __early_pfn_to_nid(unsigned long pfn) { return 0; } #else /* please see mm/page_alloc.c */ extern int __meminit early_pfn_to_nid(unsigned long pfn); #ifdef <API key> /* there is a per-arch backend function. */ extern int __meminit __early_pfn_to_nid(unsigned long pfn); #endif /* <API key> */ #endif extern void set_dma_reserve(unsigned long new_dma_reserve); extern void memmap_init_zone(unsigned long, int, unsigned long, unsigned long, enum memmap_context); extern void <API key>(void); extern int __meminit <API key>(void); extern void mem_init(void); extern void __init mmap_init(void); extern void show_mem(unsigned int flags); extern void si_meminfo(struct sysinfo * val); extern void si_meminfo_node(struct sysinfo *val, int nid); extern int after_bootmem; extern __printf(3, 4) void warn_alloc_failed(gfp_t gfp_mask, int order, const char *fmt, ...); extern void <API key>(void); extern void zone_pcp_update(struct zone *zone); extern void zone_pcp_reset(struct zone *zone); /* nommu.c */ extern atomic_long_t <API key>; extern int <API key>(struct inode *, size_t, size_t); /* interval_tree.c */ void <API key>(struct vm_area_struct *node, struct rb_root *root); void <API key>(struct vm_area_struct *node, struct vm_area_struct *prev, struct rb_root *root); void <API key>(struct vm_area_struct *node, struct rb_root *root); struct vm_area_struct *<API key>(struct rb_root *root, unsigned long start, unsigned long last); struct vm_area_struct *<API key>(struct vm_area_struct *node, unsigned long start, unsigned long last); #define <API key>(vma, root, start, last) \ for (vma = <API key>(root, start, last); \ vma; vma = <API key>(vma, start, last)) static inline void <API key>(struct vm_area_struct *vma, struct list_head *list) { list_add_tail(&vma->shared.nonlinear, list); } void <API key>(struct anon_vma_chain *node, struct rb_root *root); void <API key>(struct anon_vma_chain *node, struct rb_root *root); struct anon_vma_chain *<API key>( struct rb_root *root, unsigned long start, unsigned long last); struct anon_vma_chain *<API key>( struct anon_vma_chain *node, unsigned long start, unsigned long last); #ifdef CONFIG_DEBUG_VM_RB void <API key>(struct anon_vma_chain *node); #endif #define <API key>(avc, root, start, last) \ for (avc = <API key>(root, start, last); \ avc; avc = <API key>(avc, start, last)) /* mmap.c */ extern int __vm_enough_memory(struct mm_struct *mm, long pages, int cap_sys_admin); extern int vma_adjust(struct vm_area_struct *vma, unsigned long start, unsigned long end, pgoff_t pgoff, struct vm_area_struct *insert); extern struct vm_area_struct *vma_merge(struct mm_struct *, struct vm_area_struct *prev, unsigned long addr, unsigned long end, unsigned long vm_flags, struct anon_vma *, struct file *, pgoff_t, struct mempolicy *); extern struct anon_vma *<API key>(struct vm_area_struct *); extern int split_vma(struct mm_struct *, struct vm_area_struct *, unsigned long addr, int new_below); extern int insert_vm_struct(struct mm_struct *, struct vm_area_struct *); extern void __vma_link_rb(struct mm_struct *, struct vm_area_struct *, struct rb_node **, struct rb_node *); extern void unlink_file_vma(struct vm_area_struct *); extern struct vm_area_struct *copy_vma(struct vm_area_struct **, unsigned long addr, unsigned long len, pgoff_t pgoff, bool *need_rmap_locks); extern void exit_mmap(struct mm_struct *); extern int mm_take_all_locks(struct mm_struct *mm); extern void mm_drop_all_locks(struct mm_struct *mm); extern void set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file); extern struct file *get_mm_exe_file(struct mm_struct *mm); extern int may_expand_vm(struct mm_struct *mm, unsigned long npages); extern int <API key>(struct mm_struct *mm, unsigned long addr, unsigned long len, unsigned long flags, struct page **pages); extern unsigned long get_unmapped_area(struct file *, unsigned long, unsigned long, unsigned long, unsigned long); extern unsigned long mmap_region(struct file *file, unsigned long addr, unsigned long len, unsigned long flags, vm_flags_t vm_flags, unsigned long pgoff); extern unsigned long do_mmap_pgoff(struct file *, unsigned long, unsigned long, unsigned long, unsigned long, unsigned long); extern int do_munmap(struct mm_struct *, unsigned long, size_t); /* These take the mm semaphore themselves */ extern unsigned long vm_brk(unsigned long, unsigned long); extern int vm_munmap(unsigned long, size_t); extern unsigned long vm_mmap(struct file *, unsigned long, unsigned long, unsigned long, unsigned long, unsigned long); /* truncate.c */ extern void <API key>(struct address_space *, loff_t); extern void <API key>(struct address_space *, loff_t lstart, loff_t lend); /* generic vm_area_ops exported for stackable file systems */ extern int filemap_fault(struct vm_area_struct *, struct vm_fault *); extern int <API key>(struct vm_area_struct *vma, struct vm_fault *vmf); /* mm/page-writeback.c */ int write_one_page(struct page *page, int wait); void task_dirty_inc(struct task_struct *tsk); /* readahead.c */ #define VM_MAX_READAHEAD 128 /* kbytes */ #define VM_MIN_READAHEAD 16 /* kbytes (includes current page) */ int <API key>(struct address_space *mapping, struct file *filp, pgoff_t offset, unsigned long nr_to_read); void <API key>(struct address_space *mapping, struct file_ra_state *ra, struct file *filp, pgoff_t offset, unsigned long size); void <API key>(struct address_space *mapping, struct file_ra_state *ra, struct file *filp, struct page *pg, pgoff_t offset, unsigned long size); unsigned long max_sane_readahead(unsigned long nr); unsigned long ra_submit(struct file_ra_state *ra, struct address_space *mapping, struct file *filp); /* Generic expand stack which grows the stack according to GROWS{UP,DOWN} */ extern int expand_stack(struct vm_area_struct *vma, unsigned long address); /* <API key> still needs to to grow downwards at some places */ extern int expand_downwards(struct vm_area_struct *vma, unsigned long address); #if VM_GROWSUP extern int expand_upwards(struct vm_area_struct *vma, unsigned long address); #else #define expand_upwards(vma, address) do { } while (0) #endif /* Look up the first VMA which satisfies addr < vm_end, NULL if none. */ extern struct vm_area_struct * find_vma(struct mm_struct * mm, unsigned long addr); extern struct vm_area_struct * find_vma_prev(struct mm_struct * mm, unsigned long addr, struct vm_area_struct **pprev); /* Look up the first VMA which intersects the interval start_addr..end_addr-1, NULL if none. Assume start_addr < end_addr. */ static inline struct vm_area_struct * <API key>(struct mm_struct * mm, unsigned long start_addr, unsigned long end_addr) { struct vm_area_struct * vma = find_vma(mm,start_addr); if (vma && end_addr <= vma->vm_start) vma = NULL; return vma; } static inline unsigned long vma_pages(struct vm_area_struct *vma) { return (vma->vm_end - vma->vm_start) >> PAGE_SHIFT; } /* Look up the first VMA which exactly match the interval vm_start ... vm_end */ static inline struct vm_area_struct *find_exact_vma(struct mm_struct *mm, unsigned long vm_start, unsigned long vm_end) { struct vm_area_struct *vma = find_vma(mm, vm_start); if (vma && (vma->vm_start != vm_start || vma->vm_end != vm_end)) vma = NULL; return vma; } #ifdef CONFIG_MMU pgprot_t vm_get_page_prot(unsigned long vm_flags); #else static inline pgprot_t vm_get_page_prot(unsigned long vm_flags) { return __pgprot(0); } #endif struct vm_area_struct *find_extend_vma(struct mm_struct *, unsigned long addr); int remap_pfn_range(struct vm_area_struct *, unsigned long addr, unsigned long pfn, unsigned long size, pgprot_t); int vm_insert_page(struct vm_area_struct *, unsigned long addr, struct page *); int vm_insert_pfn(struct vm_area_struct *vma, unsigned long addr, unsigned long pfn); int vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr, unsigned long pfn); struct page *follow_page(struct vm_area_struct *, unsigned long address, unsigned int foll_flags); #define FOLL_WRITE 0x01 /* check pte is writable */ #define FOLL_TOUCH 0x02 /* mark page accessed */ #define FOLL_GET 0x04 /* do get_page on page */ #define FOLL_DUMP 0x08 /* give error on hole if it would be zero */ #define FOLL_FORCE 0x10 #define FOLL_NOWAIT 0x20 /* if a disk transfer is needed, start the IO * and return without waiting upon it */ #define FOLL_MLOCK 0x40 /* mark page as mlocked */ #define FOLL_SPLIT 0x80 /* don't return transhuge pages, split them */ #define FOLL_HWPOISON 0x100 /* check page is hwpoisoned */ typedef int (*pte_fn_t)(pte_t *pte, pgtable_t token, unsigned long addr, void *data); extern int apply_to_page_range(struct mm_struct *mm, unsigned long address, unsigned long size, pte_fn_t fn, void *data); #ifdef CONFIG_PROC_FS void vm_stat_account(struct mm_struct *, unsigned long, struct file *, long); #else static inline void vm_stat_account(struct mm_struct *mm, unsigned long flags, struct file *file, long pages) { mm->total_vm += pages; } #endif /* CONFIG_PROC_FS */ #ifdef <API key> extern void kernel_map_pages(struct page *page, int numpages, int enable); #ifdef CONFIG_HIBERNATION extern bool kernel_page_present(struct page *page); #endif /* CONFIG_HIBERNATION */ #else static inline void kernel_map_pages(struct page *page, int numpages, int enable) {} #ifdef CONFIG_HIBERNATION static inline bool kernel_page_present(struct page *page) { return true; } #endif /* CONFIG_HIBERNATION */ #endif extern struct vm_area_struct *get_gate_vma(struct mm_struct *mm); #ifdef <API key> int in_gate_area_no_mm(unsigned long addr); int in_gate_area(struct mm_struct *mm, unsigned long addr); #else int in_gate_area_no_mm(unsigned long addr); #define in_gate_area(mm, addr) ({(void)mm; in_gate_area_no_mm(addr);}) #endif /* <API key> */ int <API key>(struct ctl_table *, int, void __user *, size_t *, loff_t *); unsigned long shrink_slab(struct shrink_control *shrink, unsigned long nr_pages_scanned, unsigned long lru_pages); #ifndef CONFIG_MMU #define randomize_va_space 0 #else extern int randomize_va_space; #endif const char * arch_vma_name(struct vm_area_struct *vma); void print_vma_addr(char *prefix, unsigned long rip); void <API key>(struct page **map_map, unsigned long pnum_begin, unsigned long pnum_end, unsigned long map_count, int nodeid); struct page *<API key>(unsigned long pnum, int nid); pgd_t *<API key>(unsigned long addr, int node); pud_t *<API key>(pgd_t *pgd, unsigned long addr, int node); pmd_t *<API key>(pud_t *pud, unsigned long addr, int node); pte_t *<API key>(pmd_t *pmd, unsigned long addr, int node); void *vmemmap_alloc_block(unsigned long size, int node); void *<API key>(unsigned long size, int node); void vmemmap_verify(pte_t *, int, unsigned long, unsigned long); int <API key>(struct page *start_page, unsigned long pages, int node); int vmemmap_populate(struct page *start_page, unsigned long pages, int node); void <API key>(void); enum mf_flags { MF_COUNT_INCREASED = 1 << 0, MF_ACTION_REQUIRED = 1 << 1, MF_MUST_KILL = 1 << 2, }; extern int memory_failure(unsigned long pfn, int trapno, int flags); extern void <API key>(unsigned long pfn, int trapno, int flags); extern int unpoison_memory(unsigned long pfn); extern int <API key>; extern int <API key>; extern void shake_page(struct page *p, int access); extern atomic_long_t mce_bad_pages; extern int soft_offline_page(struct page *page, int flags); extern void dump_page(struct page *page); #if defined(<API key>) || defined(CONFIG_HUGETLBFS) extern void clear_huge_page(struct page *page, unsigned long addr, unsigned int pages_per_huge_page); extern void copy_user_huge_page(struct page *dst, struct page *src, unsigned long addr, struct vm_area_struct *vma, unsigned int pages_per_huge_page); #endif /* <API key> || CONFIG_HUGETLBFS */ #ifdef <API key> extern unsigned int <API key>; static inline unsigned int <API key>(void) { return <API key>; } static inline bool page_is_guard(struct page *page) { return test_bit(<API key>, &page->debug_flags); } #else static inline unsigned int <API key>(void) { return 0; } static inline bool page_is_guard(struct page *page) { return false; } #endif /* <API key> */ #endif /* __KERNEL__ */ #endif /* _LINUX_MM_H */
#include "die.h" #include "getconf.h" #include "getconfopt.h" #include "stralloc.h" static int parse(struct option *o,const char *arg) { stralloc_copys(o->var.str,arg); return 1; } static void fetch(struct option *o) { getconf_line(o->var.str,o->filename,0); } const struct option_type opt_str = { 1, parse, fetch };
// <API key>: GPL-2.0-or-later #include "iwMsgbox.h" #include "Loader.h" #include "WindowManager.h" #include "controls/ctrlImage.h" #include "controls/ctrlMultiline.h" #include "drivers/VideoDriverWrapper.h" #include "enum_cast.hpp" #include "helpers/EnumArray.h" #include "ogl/glArchivItem_Bitmap.h" #include "gameData/const_gui_ids.h" namespace { enum IDS { ID_ICON, ID_TEXT, ID_BT_0 }; const Extent btSize(90, 20); const unsigned short paddingX = 15; /// Padding in X/to image const unsigned short minTextWidth = 150; const unsigned short maxTextHeight = 200; } // namespace iwMsgbox::iwMsgbox(const std::string& title, const std::string& text, Window* msgHandler, MsgboxButton button, MsgboxIcon icon, unsigned msgboxid) : iwMsgbox(title, text, msgHandler, button, "io", rttr::enum_cast(icon), msgboxid) {} iwMsgbox::iwMsgbox(const std::string& title, const std::string& text, Window* msgHandler, MsgboxButton button, const ResourceId& iconFile, unsigned iconIdx, unsigned msgboxid ) : IngameWindow(CGI_MSGBOX, IngameWindow::posLastOrCenter, Extent(420, 140), title, LOADER.GetImageN("resource", 41), true, CloseBehavior::Custom), button(button), msgboxid(msgboxid), msgHandler_(msgHandler) { Init(text, iconFile, iconIdx); } void iwMsgbox::Init(const std::string& text, const ResourceId& iconFile, unsigned iconIdx) { glArchivItem_Bitmap* icon = LOADER.GetImageN(iconFile, iconIdx); if(icon) AddImage(ID_ICON, contentOffset + DrawPoint(30, 20), icon); int textX = icon ? icon->getWidth() - icon->getNx() + GetCtrl<Window>(ID_ICON)->GetPos().x : contentOffset.x; textX += paddingX; Extent txtSize = Extent(std::max<int>(minTextWidth, <API key>().x - textX - paddingX), maxTextHeight); ctrlMultiline* multiline = AddMultiline(ID_TEXT, DrawPoint(textX, contentOffset.y + 5), txtSize, TextureColor::Green2, NormalFont); multiline->ShowBackground(false); multiline->AddString(text, COLOR_YELLOW); multiline->Resize(multiline->GetContentSize()); // 10 padding, button/button padding Extent newIwSize(multiline->GetPos() + multiline->GetSize() + Extent(paddingX, 10 + btSize.y * 2)); // Increase window size if required SetIwSize(elMax(GetIwSize(), newIwSize)); unsigned defaultBt = 0; // Buttons erstellen switch(button) { case MsgboxButton::Ok: AddButton(ID_BT_0, GetSize().x / 2 - 45, _("OK"), TextureColor::Green2); defaultBt = 0; break; case MsgboxButton::OkCancel: AddButton(ID_BT_0, GetSize().x / 2 - 3 - 90, _("OK"), TextureColor::Green2); AddButton(ID_BT_0 + 1, GetSize().x / 2 + 3, _("Cancel"), TextureColor::Red1); defaultBt = 1; break; case MsgboxButton::YesNo: AddButton(ID_BT_0, GetSize().x / 2 - 3 - 90, _("Yes"), TextureColor::Green2); AddButton(ID_BT_0 + 1, GetSize().x / 2 + 3, _("No"), TextureColor::Red1); defaultBt = 1; break; case MsgboxButton::YesNoCancel: AddButton(ID_BT_0, GetSize().x / 2 - 45 - 6 - 90, _("Yes"), TextureColor::Green2); AddButton(ID_BT_0 + 1, GetSize().x / 2 - 45, _("No"), TextureColor::Red1); AddButton(ID_BT_0 + 2, GetSize().x / 2 + 45 + 6, _("Cancel"), TextureColor::Grey); defaultBt = 2; break; } const Window* defBt = GetCtrl<Window>(defaultBt + ID_BT_0); if(defBt) VIDEODRIVER.SetMousePos(defBt->GetDrawPos() + DrawPoint(defBt->GetSize()) / 2); WINDOWMANAGER.SetCursor(); } iwMsgbox::~iwMsgbox() = default; void iwMsgbox::MoveIcon(const DrawPoint& pos) { auto* icon = GetCtrl<ctrlImage>(ID_ICON); if(icon) { icon->SetPos(elMax(pos, DrawPoint(0, 0))); const ITexture* iconImg = icon->GetImage(); DrawPoint iconPos(icon->GetPos() - iconImg->GetOrigin()); DrawPoint textPos = contentOffset + DrawPoint(paddingX, 5); Extent textMaxSize; if(iconPos.x < 100) { // icon left textPos.x = iconPos.x + iconImg->GetSize().x + paddingX; textMaxSize.x = std::max<int>(minTextWidth, 400 - textPos.x - paddingX); textMaxSize.y = maxTextHeight; } else if(iconPos.x > 300) { // icon right textMaxSize.x = iconPos.x - 2 * paddingX; textMaxSize.y = maxTextHeight; } else if(iconPos.y + iconImg->GetSize().y < 50) { // icon top textPos.y = iconPos.y + iconImg->GetSize().x + paddingX; textMaxSize.x = 400 - 2 * paddingX; textMaxSize.y = maxTextHeight; } else if(iconPos.y > 150) { // icon bottom textMaxSize.x = 400 - 2 * paddingX; textMaxSize.y = iconPos.y - textPos.y; } else { // Icon middle -> Overlay text textMaxSize.x = 400 - 2 * paddingX; textMaxSize.y = maxTextHeight; } auto* multiline = GetCtrl<ctrlMultiline>(ID_TEXT); multiline->SetPos(textPos); multiline->Resize(textMaxSize); multiline->Resize(multiline->GetContentSize()); DrawPoint newSize = iconPos + DrawPoint(iconImg->GetSize()); newSize = elMax(newSize, multiline->GetPos() + DrawPoint(multiline->GetSize()) + DrawPoint::all(paddingX)); newSize += DrawPoint(0, 10 + btSize.y * 2) + DrawPoint(contentOffsetEnd); DrawPoint btMoveDelta(newSize - GetSize()); btMoveDelta.x /= 2; for(unsigned i = 0; i < 3; i++) { auto* bt = GetCtrl<Window>(i + ID_BT_0); if(bt) bt->SetPos(bt->GetPos() + btMoveDelta); } Resize(Extent(newSize)); } } constexpr helpers::EnumArray<std::array<MsgboxResult, 3>, MsgboxButton> RET_IDS = { {{MsgboxResult::Ok}, {MsgboxResult::Ok, MsgboxResult::Cancel}, {MsgboxResult::Yes, MsgboxResult::No}, {MsgboxResult::Yes, MsgboxResult::No, MsgboxResult::Cancel}}}; void iwMsgbox::Msg_ButtonClick(const unsigned ctrl_id) { if(msgHandler_) msgHandler_->Msg_MsgBoxResult(msgboxid, RET_IDS[button][ctrl_id - ID_BT_0]); Close(); } void iwMsgbox::AddButton(unsigned short id, int x, const std::string& text, const TextureColor tc) { AddTextButton(id, DrawPoint(x, <API key>().y - btSize.y * 2), btSize, tc, text, NormalFont); }
<!DOCTYPE html> <html lang="en-US"> <head> <title>Tryit Editor v2.3</title> <meta id="viewport" name='viewport'> <script> (function() { if ( navigator.userAgent.match(/iPad/i) ) { document.getElementById('viewport').setAttribute("content", "width=device-width, initial-scale=0.9"); } }()); </script> <link rel="stylesheet" href="../trycss.css"> <!--[if lt IE 8]> <style> .textareacontainer, .iframecontainer {width:48%;} .textarea, .iframe {height:800px;} #textareaCode, #iframeResult {height:700px;} .menu img {display:none;} </style> <![endif] <script> (function(i,s,o,g,r,a,m){i['<API key>']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.<API key>(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','../../www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-3855518-1', 'auto'); ga('require', 'displayfeatures'); ga('send', 'pageview'); </script> <script> var googletag = googletag || {}; googletag.cmd = googletag.cmd || []; (function() { var gads = document.createElement('script'); gads.async = true; gads.type = 'text/javascript'; var useSSL = 'https:' == document.location.protocol; gads.src = (useSSL ? 'https:' : 'http:') + ' var node = document.<API key>('script')[0]; node.parentNode.insertBefore(gads, node); })(); </script> <script> googletag.cmd.push(function() { googletag.defineSlot('/16833175/TryitLeaderboard', [[728, 90], [970, 90]], '<API key>').addService(googletag.pubads()); googletag.pubads().setTargeting("content","tryjquery"); googletag.pubads().enableSingleRequest(); googletag.enableServices(); }); </script> <script type="text/javascript"> function submitTryit() { var t=document.getElementById("textareaCode").value; t=t.replace(/=/gi,"w3equalsign"); var pos=t.search(/script/i) while (pos>0) { t=t.substring(0,pos) + "w3" + t.substr(pos,3) + "w3" + t.substr(pos+3,3) + "tag" + t.substr(pos+6); pos=t.search(/script/i); } if ( navigator.userAgent.match(/Safari/i) ) { t=escape(t); document.getElementById("bt").value="1"; } document.getElementById("code").value=t; document.getElementById("tryitform").action="tryit_view52a0.html?x=" + Math.random(); validateForm(); document.getElementById("iframeResult").contentWindow.name = "view"; document.getElementById("tryitform").submit(); } function validateForm() { var code=document.getElementById("code").value; if (code.length>8000) { document.getElementById("code").value="<h1>Error</h1>"; } } </script> <style> </style> </head> <body> <div id="ads"> <div style="position:relative;width:100%;margin-top:0px;margin-bottom:0px;"> <div style="width:974px;height:94px;position:relative;margin:0px;margin-top:5px;margin-bottom:5px;margin-right:auto;margin-left:auto;padding:0px;overflow:hidden;"> <!-- TryitLeaderboard --> <div id='<API key>' style='width:970px; height:90px;'> <script type='text/javascript'> googletag.cmd.push(function() { googletag.display('<API key>'); }); </script> </div> <div style="clear:both"></div> </div> </div> </div> <div class="container"> <div class="textareacontainer"> <div class="textarea"> <div class="headerText" style="width:auto;float:left;">Edit This Code:</div> <div class="headerBtnDiv" style="width:auto;float:right;margin-top:8px;margin-right:2.4%;"><button class="submit" type="button" onclick="submitTryit()">See Result &raquo;</button></div> <div class="textareawrapper"> <textarea autocomplete="off" class="code_input" id="textareaCode" wrap="logical" xrows="30" xcols="50"><!DOCTYPE html> <html> <head> <script src="../../ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script> $(document).ready(function(){ $(".btn1").click(function(){ $("p").animate({top:"100px"}); }); $(".btn2").click(function(){ $("p").animate({top:"0px"}); }); }); </script> </head> <body> <button class="btn1">Animate</button> <button class="btn2">Reset</button> <p style="position:relative">This is a paragraph.</p> </body> </html> </textarea> <form autocomplete="off" style="margin:0px;display:none;" action="http: <input type="hidden" name="code" id="code" /> <input type="hidden" id="bt" name="bt" /> </form> </div> </div> </div> <div class="iframecontainer"> <div class="iframe"> <div class="headerText resultHeader">Result:</div> <div class="iframewrapper"> <iframe id="iframeResult" class="result_output" frameborder="0" name="view" xsrc="<API key>.html"></iframe> </div> <div class="footerText">Try it Yourself - &copy; <a href="../index.html">w3schools.com</a></div> </div> </div> </div> <script>submitTryit()</script> </body> </html>
#pragma once #include <vector> #include <ostream> #include <algorithm> #include "SpeciesTypeID.hpp" #include "ReactionRuleID.hpp" #include "Reactants.hpp" class ReactionRule { public: using reactants = Reactants<SpeciesTypeID, SpeciesTypeID>; using products = std::vector<SpeciesTypeID>; explicit ReactionRule(const SpeciesTypeID s1, double k, const products& products) : ReactionRule(reactants(s1), k, products) {} explicit ReactionRule(const SpeciesTypeID s1, const SpeciesTypeID s2, double k, const products& products) : ReactionRule(reactants(s1, s2), k, products) {} explicit ReactionRule(const reactants& reactants, double k, const products& products) : id_(), reactants_(reactants), products_(products), k_(k) { THROW_UNLESS_MSG(illegal_argument, reactants_.size() > 0, "ReactionRule need at least one SpeciesTypeID"); std::sort(products_.begin(), products_.end()); // sort for easier duplicate checks } ReactionRuleID id() const { return id_; } double getK() const { return k_; } const reactants& get_reactants() const { return reactants_; } const products& get_products() const { return products_; } bool operator<(const ReactionRule& rhs) const { // compare reactants and products (ignore id and k) will detect duplicates in set if (reactants_ < rhs.get_reactants()) return true; return reactants_ == rhs.get_reactants() ? products_ < rhs.get_products() : false; } bool operator==(const ReactionRule& rhs) const { return reactants_ == rhs.get_reactants() && products_ == rhs.get_products() && k_ == rhs.k_; } bool operator!=(const ReactionRule& rhs) const { return !(*this == rhs); } static ReactionRule empty() { return ReactionRule(SpeciesTypeID(1), 0.0, std::vector<SpeciesTypeID>()); } protected: friend class <API key>; void set_id(const ReactionRuleID id) { ASSERT(id); id_ = id; } friend class Persistence; private: ReactionRuleID id_; reactants reactants_; products products_; double k_; }; inline std::ostream& operator<<(std::ostream& stream, const ReactionRule& rr) { stream << "ReactionRule{" << rr.id() << ", reactants=[" << rr.get_reactants(); stream << "], k=" << rr.getK() << ", products=["; bool first = true; for (auto& p : rr.get_products()) { if (!first) stream << ", "; stream << p; first = false; } stream << "]}"; return stream; }
#include "outputfile.h" #include <iostream> using namespace std; void OutputFile::create() throw(NLXError) { // Data file exists? if ( !force ) { open(filename.c_str(),ios::in); bool exists = good(); close(); clear(); if ( exists ) throw NLXError(NLXError::WRITE_ERROR,"'" + filename + "' exists."); } // Create data file open(filename.c_str(),mode); if ( !good() ) throw NLXError(NLXError::WRITE_ERROR,"could not create '" + filename + "'."); }
#ifndef _LINUX_MMZONE_H #define _LINUX_MMZONE_H #ifndef __ASSEMBLY__ #ifndef <API key> #include <linux/spinlock.h> #include <linux/list.h> #include <linux/wait.h> #include <linux/bitops.h> #include <linux/cache.h> #include <linux/threads.h> #include <linux/numa.h> #include <linux/init.h> #include <linux/seqlock.h> #include <linux/nodemask.h> #include <linux/pageblock-flags.h> #include <generated/bounds.h> #include <linux/atomic.h> #include <asm/page.h> /* Free memory management - zoned buddy allocator. */ #ifndef <API key> #define MAX_ORDER 11 #else #define MAX_ORDER <API key> #endif #define MAX_ORDER_NR_PAGES (1 << (MAX_ORDER - 1)) /* * <API key> is the order at which allocations are deemed * costly to service. That is between allocation orders which should * coelesce naturally under reasonable reclaim pressure and those which * will not. */ #define <API key> 3 #define MIGRATE_UNMOVABLE 0 #define MIGRATE_RECLAIMABLE 1 #define MIGRATE_MOVABLE 2 #define MIGRATE_PCPTYPES 3 /* the number of types on the pcp lists */ #define MIGRATE_RESERVE 3 #define MIGRATE_ISOLATE 4 /* can't allocate from here */ #define MIGRATE_TYPES 5 #define <API key>(order, type) \ for (order = 0; order < MAX_ORDER; order++) \ for (type = 0; type < MIGRATE_TYPES; type++) extern int <API key>; static inline int <API key>(struct page *page) { return <API key>(page, PB_migrate, PB_migrate_end); } struct free_area { struct list_head free_list[MIGRATE_TYPES]; unsigned long nr_free; }; struct pglist_data; /* * zone->lock and zone->lru_lock are two of the hottest locks in the kernel. * So add a wild amount of padding here to ensure that they fall into separate * cachelines. There are very few zone structures in the machine, so space * consumption is not a concern here. */ #if defined(CONFIG_SMP) struct zone_padding { char x[0]; } <API key>; #define ZONE_PADDING(name) struct zone_padding name; #else #define ZONE_PADDING(name) #endif enum zone_stat_item { /* First 128 byte cacheline (assuming 64 bit words) */ NR_FREE_PAGES, NR_LRU_BASE, NR_INACTIVE_ANON = NR_LRU_BASE, /* must match order of LRU_[IN]ACTIVE */ NR_ACTIVE_ANON, NR_INACTIVE_FILE, NR_ACTIVE_FILE, NR_UNEVICTABLE, NR_MLOCK, /* mlock()ed pages found and moved off LRU */ NR_ANON_PAGES, /* Mapped anonymous pages */ NR_FILE_MAPPED, /* pagecache pages mapped into pagetables. only modified from process context */ NR_FILE_PAGES, NR_FILE_DIRTY, NR_WRITEBACK, NR_SLAB_RECLAIMABLE, <API key>, NR_PAGETABLE, /* used for pagetables */ NR_KERNEL_STACK, /* Second 128 byte cacheline */ NR_UNSTABLE_NFS, /* NFS unstable pages */ NR_BOUNCE, NR_VMSCAN_WRITE, NR_VMSCAN_IMMEDIATE, /* Prioritise for reclaim when writeback ends */ NR_WRITEBACK_TEMP, /* Writeback using temporary buffers */ NR_ISOLATED_ANON, /* Temporary isolated pages from anon lru */ NR_ISOLATED_FILE, /* Temporary isolated pages from file lru */ NR_SHMEM, /* shmem pages (included tmpfs/GEM pages) */ NR_DIRTIED, /* page dirtyings since bootup */ NR_WRITTEN, /* page writings since bootup */ #ifdef CONFIG_NUMA NUMA_HIT, /* allocated in intended node */ NUMA_MISS, /* allocated in non intended node */ NUMA_FOREIGN, /* was intended here, hit elsewhere */ NUMA_INTERLEAVE_HIT, /* interleaver preferred this zone */ NUMA_LOCAL, /* allocation from local node */ NUMA_OTHER, /* allocation from other node */ #endif <API key>, <API key> }; /* * We do arithmetic on the LRU lists in various places in the code, * so it is important to keep the active lists LRU_ACTIVE higher in * the array than the corresponding inactive lists, and to keep * the *_FILE lists LRU_FILE higher than the corresponding _ANON lists. * * This has to be kept in sync with the statistics in zone_stat_item * above and the descriptions in vmstat_text in mm/vmstat.c */ #define LRU_BASE 0 #define LRU_ACTIVE 1 #define LRU_FILE 2 enum lru_list { LRU_INACTIVE_ANON = LRU_BASE, LRU_ACTIVE_ANON = LRU_BASE + LRU_ACTIVE, LRU_INACTIVE_FILE = LRU_BASE + LRU_FILE, LRU_ACTIVE_FILE = LRU_BASE + LRU_FILE + LRU_ACTIVE, LRU_UNEVICTABLE, NR_LRU_LISTS }; #define for_each_lru(lru) for (lru = 0; lru < NR_LRU_LISTS; lru++) #define <API key>(lru) for (lru = 0; lru <= LRU_ACTIVE_FILE; lru++) static inline int is_file_lru(enum lru_list lru) { return (lru == LRU_INACTIVE_FILE || lru == LRU_ACTIVE_FILE); } static inline int is_active_lru(enum lru_list lru) { return (lru == LRU_ACTIVE_ANON || lru == LRU_ACTIVE_FILE); } static inline int is_unevictable_lru(enum lru_list lru) { return (lru == LRU_UNEVICTABLE); } struct lruvec { struct list_head lists[NR_LRU_LISTS]; }; /* Mask used at gathering information at once (see memcontrol.c) */ #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE)) #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON)) #define LRU_ALL_EVICTABLE (LRU_ALL_FILE | LRU_ALL_ANON) #define LRU_ALL ((1 << NR_LRU_LISTS) - 1) /* Isolate inactive pages */ #define ISOLATE_INACTIVE ((__force isolate_mode_t)0x1) /* Isolate active pages */ #define ISOLATE_ACTIVE ((__force isolate_mode_t)0x2) /* Isolate clean file */ #define ISOLATE_CLEAN ((__force isolate_mode_t)0x4) /* Isolate unmapped file */ #define ISOLATE_UNMAPPED ((__force isolate_mode_t)0x8) /* Isolate for asynchronous migration */ #define <API key> ((__force isolate_mode_t)0x10) /* LRU Isolation modes. */ typedef unsigned __bitwise__ isolate_mode_t; enum zone_watermarks { WMARK_MIN, WMARK_LOW, WMARK_HIGH, NR_WMARK }; #define min_wmark_pages(z) (z->watermark[WMARK_MIN]) #define low_wmark_pages(z) (z->watermark[WMARK_LOW]) #define high_wmark_pages(z) (z->watermark[WMARK_HIGH]) struct per_cpu_pages { int count; /* number of pages in the list */ int high; /* high watermark, emptying needed */ int batch; /* chunk size for buddy add/remove */ /* Lists of pages, one per migrate type stored on the pcp-lists */ struct list_head lists[MIGRATE_PCPTYPES]; }; struct per_cpu_pageset { struct per_cpu_pages pcp; #ifdef CONFIG_NUMA s8 expire; #endif #ifdef CONFIG_SMP s8 stat_threshold; s8 vm_stat_diff[<API key>]; #endif }; #endif /* !__GENERATING_BOUNDS.H */ enum zone_type { #ifdef CONFIG_ZONE_DMA ZONE_DMA, #endif #ifdef CONFIG_ZONE_DMA32 /* * x86_64 needs two ZONE_DMAs because it supports devices that are * only able to do DMA to the lower 16M but also 32 bit devices that * can only do DMA areas below 4G. */ ZONE_DMA32, #endif /* * Normal addressable memory is in ZONE_NORMAL. DMA operations can be * performed on pages in ZONE_NORMAL if the DMA devices support * transfers to all addressable memory. */ ZONE_NORMAL, #ifdef CONFIG_HIGHMEM /* * A memory area that is only addressable by the kernel through * mapping portions into its own address space. This is for example * used by i386 to allow the kernel to address the memory beyond * 900MB. The kernel will set up special mappings (page * table entries on i386) for each page that the kernel needs to * access. */ ZONE_HIGHMEM, #endif ZONE_MOVABLE, __MAX_NR_ZONES }; #ifndef <API key> /* * When a memory allocation must conform to specific limitations (such * as being suitable for DMA) the caller will pass in hints to the * allocator in the gfp_mask, in the zone modifier bits. These bits * are used to select a priority ordered list of memory zones which * match the requested limits. See gfp_zone() in include/linux/gfp.h */ #if MAX_NR_ZONES < 2 #define ZONES_SHIFT 0 #elif MAX_NR_ZONES <= 2 #define ZONES_SHIFT 1 #elif MAX_NR_ZONES <= 4 #define ZONES_SHIFT 2 #else #error ZONES_SHIFT -- too many zones configured adjust calculation #endif struct zone_reclaim_stat { /* * The pageout code in vmscan.c keeps track of how many of the * mem/swap backed and file backed pages are refeferenced. * The higher the rotated/scanned ratio, the more valuable * that cache is. * * The anon LRU stats live in [0], file LRU stats in [1] */ unsigned long recent_rotated[2]; unsigned long recent_scanned[2]; }; struct zone { /* Fields commonly accessed by the page allocator */ /* zone watermarks, access with *_wmark_pages(zone) macros */ unsigned long watermark[NR_WMARK]; /* * When free pages are below this point, additional steps are taken * when reading the number of free pages to avoid per-cpu counter * drift allowing watermarks to be breached */ unsigned long percpu_drift_mark; /* * We don't know if the memory that we're going to allocate will be freeable * or/and it will be released eventually, so to avoid totally wasting several * GB of ram we must reserve some of the lower zone memory (otherwise we risk * to run OOM on the lower zones despite there's tons of freeable ram * on the higher zones). This array is recalculated at runtime if the * <API key> sysctl changes. */ unsigned long lowmem_reserve[MAX_NR_ZONES]; /* * This is a per-zone reserve of pages that should not be * considered dirtyable memory. */ unsigned long <API key>; #ifdef CONFIG_NUMA int node; /* * zone reclaim becomes active if more unmapped pages exist. */ unsigned long min_unmapped_pages; unsigned long min_slab_pages; #endif struct per_cpu_pageset __percpu *pageset; /* * free areas of different sizes */ spinlock_t lock; int all_unreclaimable; /* All pages pinned */ #ifdef <API key> /* see spanned/present_pages for more description */ seqlock_t span_seqlock; #endif struct free_area free_area[MAX_ORDER]; #ifndef CONFIG_SPARSEMEM /* * Flags for a pageblock_nr_pages block. See pageblock-flags.h. * In SPARSEMEM, this map is stored in struct mem_section */ unsigned long *pageblock_flags; #endif /* CONFIG_SPARSEMEM */ #ifdef CONFIG_COMPACTION /* * On compaction failure, 1<<compact_defer_shift compactions * are skipped before trying again. The number attempted since * last failure is tracked with compact_considered. */ unsigned int compact_considered; unsigned int compact_defer_shift; int <API key>; #endif ZONE_PADDING(_pad1_) /* Fields commonly accessed by the page reclaim scanner */ spinlock_t lru_lock; struct lruvec lruvec; struct zone_reclaim_stat reclaim_stat; unsigned long pages_scanned; /* since last reclaim */ unsigned long flags; /* zone flags, see below */ /* Zone statistics */ atomic_long_t vm_stat[<API key>]; /* * The target ratio of ACTIVE_ANON to INACTIVE_ANON pages on * this zone's LRU. Maintained by the pageout code. */ unsigned int inactive_ratio; ZONE_PADDING(_pad2_) /* Rarely used or read-mostly fields */ /* * wait_table -- the array holding the hash table * <API key> -- the size of the hash table array * wait_table_bits -- wait_table_size == (1 << wait_table_bits) * * The purpose of all these is to keep track of the people * waiting for a page to become available and make them * runnable again when possible. The trouble is that this * consumes a lot of space, especially when so few things * wait on pages at a given time. So instead of using * per-page waitqueues, we use a waitqueue hash table. * * The bucket discipline is to sleep on the same queue when * colliding and wake all in that wait queue when removing. * When something wakes, it must check to be sure its page is * truly available, a la thundering herd. The cost of a * collision is great, but given the expected load of the * table, they should be so rare as to be outweighed by the * benefits from the saved space. * * <API key>() and unlock_page() in mm/filemap.c, are the * primary users of these fields, and in mm/page_alloc.c * free_area_init_core() performs the initialization of them. */ wait_queue_head_t * wait_table; unsigned long <API key>; unsigned long wait_table_bits; /* * Discontig memory support fields. */ struct pglist_data *zone_pgdat; /* zone_start_pfn == zone_start_paddr >> PAGE_SHIFT */ unsigned long zone_start_pfn; /* * zone_start_pfn, spanned_pages and present_pages are all * protected by span_seqlock. It is a seqlock because it has * to be read outside of zone->lock, and it is done in the main * allocator path. But, it is written quite infrequently. * * The lock is declared along with zone->lock because it is * frequently read in proximity to zone->lock. It's good to * give them a chance of being in the same cacheline. */ unsigned long spanned_pages; /* total size, including holes */ unsigned long present_pages; /* amount of memory (excluding holes) */ /* * rarely used fields: */ const char *name; } <API key>; typedef enum { ZONE_RECLAIM_LOCKED, /* prevents concurrent reclaim */ ZONE_OOM_LOCKED, /* zone is in OOM killer zonelist */ ZONE_CONGESTED, /* zone has many dirty pages backed by * a congested BDI */ } zone_flags_t; static inline void zone_set_flag(struct zone *zone, zone_flags_t flag) { set_bit(flag, &zone->flags); } static inline int <API key>(struct zone *zone, zone_flags_t flag) { return test_and_set_bit(flag, &zone->flags); } static inline void zone_clear_flag(struct zone *zone, zone_flags_t flag) { clear_bit(flag, &zone->flags); } static inline int <API key>(const struct zone *zone) { return test_bit(ZONE_CONGESTED, &zone->flags); } static inline int <API key>(const struct zone *zone) { return test_bit(ZONE_RECLAIM_LOCKED, &zone->flags); } static inline int zone_is_oom_locked(const struct zone *zone) { return test_bit(ZONE_OOM_LOCKED, &zone->flags); } /* * The "priority" of VM scanning is how much of the queues we will scan in one * go. A value of 12 for DEF_PRIORITY implies that we will scan 1/4096th of the * queues ("queue_length >> 12") during an aging round. */ #define DEF_PRIORITY 12 /* Maximum number of zones on a zonelist */ #define <API key> (MAX_NUMNODES * MAX_NR_ZONES) #ifdef CONFIG_NUMA /* * The NUMA zonelists are doubled because we need zonelists that restrict the * allocations to a single node for GFP_THISNODE. * * [0] : Zonelist with fallback * [1] : No fallback (GFP_THISNODE) */ #define MAX_ZONELISTS 2 /* * We cache key information from each zonelist for smaller cache * footprint when scanning for free pages in <API key>(). * * 1) The BITMAP fullzones tracks which zones in a zonelist have come * up short of free memory since the last time (last_fullzone_zap) * we zero'd fullzones. * 2) The array z_to_n[] maps each zone in the zonelist to its node * id, so that we can efficiently evaluate whether that node is * set in the current tasks mems_allowed. * * Both fullzones and z_to_n[] are one-to-one with the zonelist, * indexed by a zones offset in the zonelist zones[] array. * * The <API key>() routine does two scans. During the * first scan, we skip zones whose corresponding bit in 'fullzones' * is set or whose corresponding node in current->mems_allowed (which * comes from cpusets) is not set. During the second scan, we bypass * this zonelist_cache, to ensure we look methodically at each zone. * * Once per second, we zero out (zap) fullzones, forcing us to * reconsider nodes that might have regained more free memory. * The field last_full_zap is the time we last zapped fullzones. * * This mechanism reduces the amount of time we waste repeatedly * reexaming zones for free memory when they just came up low on * memory momentarilly ago. * * The zonelist_cache struct members logically belong in struct * zonelist. However, the mempolicy zonelists constructed for * MPOL_BIND are intentionally variable length (and usually much * shorter). A general purpose mechanism for handling structs with * multiple variable length members is more mechanism than we want * here. We resort to some special case hackery instead. * * The MPOL_BIND zonelists don't need this zonelist_cache (in good * part because they are shorter), so we put the fixed length stuff * at the front of the zonelist struct, ending in a variable length * zones[], as is needed by MPOL_BIND. * * Then we put the optional zonelist cache on the end of the zonelist * struct. This optional stuff is found by a 'zlcache_ptr' pointer in * the fixed length portion at the front of the struct. This pointer * both enables us to find the zonelist cache, and in the case of * MPOL_BIND zonelists, (which will just set the zlcache_ptr to NULL) * to know that the zonelist cache is not there. * * The end result is that struct zonelists come in two flavors: * 1) The full, fixed length version, shown below, and * 2) The custom zonelists for MPOL_BIND. * The custom MPOL_BIND zonelists have a NULL zlcache_ptr and no zlcache. * * Even though there may be multiple CPU cores on a node modifying * fullzones or last_full_zap in the same zonelist_cache at the same * time, we don't lock it. This is just hint data - if it is wrong now * and then, the allocator will still function, perhaps a bit slower. */ struct zonelist_cache { unsigned short z_to_n[<API key>]; /* zone->nid */ DECLARE_BITMAP(fullzones, <API key>); /* zone full? */ unsigned long last_full_zap; /* when last zap'd (jiffies) */ }; #else #define MAX_ZONELISTS 1 struct zonelist_cache; #endif /* * This struct contains information about a zone in a zonelist. It is stored * here to avoid dereferences into large structures and lookups of tables */ struct zoneref { struct zone *zone; /* Pointer to actual zone */ int zone_idx; /* zone_idx(zoneref->zone) */ }; /* * One allocation request operates on a zonelist. A zonelist * is a list of zones, the first one is the 'goal' of the * allocation, the other zones are fallback zones, in decreasing * priority. * * If zlcache_ptr is not NULL, then it is just the address of zlcache, * as explained above. If zlcache_ptr is NULL, there is no zlcache. * * * To speed the reading of the zonelist, the zonerefs contain the zone index * of the entry being read. Helper functions to access information given * a struct zoneref are * * zonelist_zone() - Return the struct zone * for an entry in _zonerefs * zonelist_zone_idx() - Return the index of the zone for an entry * zonelist_node_idx() - Return the index of the node for an entry */ struct zonelist { struct zonelist_cache *zlcache_ptr; // NULL or &zlcache struct zoneref _zonerefs[<API key> + 1]; #ifdef CONFIG_NUMA struct zonelist_cache zlcache; // optional ... #endif }; #ifdef <API key> struct node_active_region { unsigned long start_pfn; unsigned long end_pfn; int nid; }; #endif /* <API key> */ #ifndef CONFIG_DISCONTIGMEM /* The array of struct pages - for discontigmem use pgdat->lmem_map */ extern struct page *mem_map; #endif /* * The pg_data_t structure is used in machines with CONFIG_DISCONTIGMEM * (mostly NUMA machines?) to denote a higher-level memory zone than the * zone denotes. * * On NUMA machines, each NUMA node would have a pg_data_t to describe * it's memory layout. * * Memory statistics and page replacement data structures are maintained on a * per-zone basis. */ struct bootmem_data; typedef struct pglist_data { struct zone node_zones[MAX_NR_ZONES]; struct zonelist node_zonelists[MAX_ZONELISTS]; int nr_zones; #ifdef <API key> /* means !SPARSEMEM */ struct page *node_mem_map; #ifdef <API key> struct page_cgroup *node_page_cgroup; #endif #endif #ifndef CONFIG_NO_BOOTMEM struct bootmem_data *bdata; #endif #ifdef <API key> /* * Must be held any time you expect node_start_pfn, node_present_pages * or node_spanned_pages stay constant. Holding this will also * guarantee that any pfn_valid() stays that way. * * Nests above zone->lock and zone->size_seqlock. */ spinlock_t node_size_lock; #endif unsigned long node_start_pfn; unsigned long node_present_pages; /* total number of physical pages */ unsigned long node_spanned_pages; /* total size of physical page range, including holes */ int node_id; wait_queue_head_t kswapd_wait; //struct task_struct *kswapd; struct task_struct *kswapd; /* Protected by lock_memory_hotplug() */ int kswapd_max_order; enum zone_type classzone_idx; } pg_data_t; #define node_present_pages(nid) (NODE_DATA(nid)->node_present_pages) #define node_spanned_pages(nid) (NODE_DATA(nid)->node_spanned_pages) #ifdef <API key> #define pgdat_page_nr(pgdat, pagenr) ((pgdat)->node_mem_map + (pagenr)) #else #define pgdat_page_nr(pgdat, pagenr) pfn_to_page((pgdat)->node_start_pfn + (pagenr)) #endif #define nid_page_nr(nid, pagenr) pgdat_page_nr(NODE_DATA(nid),(pagenr)) #define node_start_pfn(nid) (NODE_DATA(nid)->node_start_pfn) #define node_end_pfn(nid) ({\ pg_data_t *__pgdat = NODE_DATA(nid);\ __pgdat->node_start_pfn + __pgdat->node_spanned_pages;\ }) #include <linux/memory_hotplug.h> extern struct mutex zonelists_mutex; void build_all_zonelists(void *data); void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx); bool zone_watermark_ok(struct zone *z, int order, unsigned long mark, int classzone_idx, int alloc_flags); bool <API key>(struct zone *z, int order, unsigned long mark, int classzone_idx, int alloc_flags); enum memmap_context { MEMMAP_EARLY, MEMMAP_HOTPLUG, }; extern int <API key>(struct zone *zone, unsigned long start_pfn, unsigned long size, enum memmap_context context); #ifdef <API key> void memory_present(int nid, unsigned long start, unsigned long end); #else static inline void memory_present(int nid, unsigned long start, unsigned long end) {} #endif #ifdef <API key> int local_memory_node(int node_id); #else static inline int local_memory_node(int node_id) { return node_id; }; #endif #ifdef <API key> unsigned long __init <API key>(int, unsigned long, unsigned long); #endif /* * zone_idx() returns 0 for the ZONE_DMA zone, 1 for the ZONE_NORMAL zone, etc. */ #define zone_idx(zone) ((zone) - (zone)->zone_pgdat->node_zones) static inline int populated_zone(struct zone *zone) { return (!!zone->present_pages); } extern int movable_zone; static inline int <API key>(void) { #if defined(CONFIG_HIGHMEM) && defined(<API key>) return movable_zone == ZONE_HIGHMEM; #else return 0; #endif } static inline int is_highmem_idx(enum zone_type idx) { #ifdef CONFIG_HIGHMEM return (idx == ZONE_HIGHMEM || (idx == ZONE_MOVABLE && <API key>())); #else return 0; #endif } static inline int is_normal_idx(enum zone_type idx) { return (idx == ZONE_NORMAL); } /** * is_highmem - helper function to quickly check if a struct zone is a * highmem zone or not. This is an attempt to keep references * to ZONE_{DMA/NORMAL/HIGHMEM/etc} in general code to a minimum. * @zone - pointer to struct zone variable */ static inline int is_highmem(struct zone *zone) { #ifdef CONFIG_HIGHMEM int zone_off = (char *)zone - (char *)zone->zone_pgdat->node_zones; return zone_off == ZONE_HIGHMEM * sizeof(*zone) || (zone_off == ZONE_MOVABLE * sizeof(*zone) && <API key>()); #else return 0; #endif } static inline int is_normal(struct zone *zone) { return zone == zone->zone_pgdat->node_zones + ZONE_NORMAL; } static inline int is_dma32(struct zone *zone) { #ifdef CONFIG_ZONE_DMA32 return zone == zone->zone_pgdat->node_zones + ZONE_DMA32; #else return 0; #endif } static inline int is_dma(struct zone *zone) { #ifdef CONFIG_ZONE_DMA return zone == zone->zone_pgdat->node_zones + ZONE_DMA; #else return 0; #endif } /* These two functions are used to setup the per zone pages min values */ struct ctl_table; int <API key>(struct ctl_table *, int, void __user *, size_t *, loff_t *); extern int <API key>[MAX_NR_ZONES-1]; int <API key>(struct ctl_table *, int, void __user *, size_t *, loff_t *); int <API key>(struct ctl_table *, int, void __user *, size_t *, loff_t *); int <API key>(struct ctl_table *, int, void __user *, size_t *, loff_t *); int <API key>(struct ctl_table *, int, void __user *, size_t *, loff_t *); extern int <API key>(struct ctl_table *, int, void __user *, size_t *, loff_t *); extern char numa_zonelist_order[]; #define <API key> 16 /* string buffer size */ #ifndef <API key> extern struct pglist_data contig_page_data; #define NODE_DATA(nid) (&contig_page_data) #define NODE_MEM_MAP(nid) mem_map #else /* <API key> */ #include <asm/mmzone.h> #endif /* !<API key> */ extern struct pglist_data *first_online_pgdat(void); extern struct pglist_data *next_online_pgdat(struct pglist_data *pgdat); extern struct zone *next_zone(struct zone *zone); /** * <API key> - helper macro to iterate over all online nodes * @pgdat - pointer to a pg_data_t variable */ #define <API key>(pgdat) \ for (pgdat = first_online_pgdat(); \ pgdat; \ pgdat = next_online_pgdat(pgdat)) /** * for_each_zone - helper macro to iterate over all memory zones * @zone - pointer to struct zone variable * * The user only needs to declare the zone variable, for_each_zone * fills it in. */ #define for_each_zone(zone) \ for (zone = (first_online_pgdat())->node_zones; \ zone; \ zone = next_zone(zone)) #define <API key>(zone) \ for (zone = (first_online_pgdat())->node_zones; \ zone; \ zone = next_zone(zone)) \ if (!populated_zone(zone)) \ ; /* do nothing */ \ else static inline struct zone *zonelist_zone(struct zoneref *zoneref) { return zoneref->zone; } static inline int zonelist_zone_idx(struct zoneref *zoneref) { return zoneref->zone_idx; } static inline int zonelist_node_idx(struct zoneref *zoneref) { #ifdef CONFIG_NUMA /* zone_to_nid not available in this context */ return zoneref->zone->node; #else return 0; #endif /* CONFIG_NUMA */ } /** * next_zones_zonelist - Returns the next zone at or below highest_zoneidx within the allowed nodemask using a cursor within a zonelist as a starting point * @z - The cursor used as a starting point for the search * @highest_zoneidx - The zone index of the highest zone to return * @nodes - An optional nodemask to filter the zonelist with * @zone - The first suitable zone found is returned via this parameter * * This function returns the next zone at or below a given zone index that is * within the allowed nodemask using a cursor as the starting point for the * search. The zoneref returned is a cursor that represents the current zone * being examined. It should be advanced by one before calling * next_zones_zonelist again. */ struct zoneref *next_zones_zonelist(struct zoneref *z, enum zone_type highest_zoneidx, nodemask_t *nodes, struct zone **zone); /** * <API key> - Returns the first zone at or below highest_zoneidx within the allowed nodemask in a zonelist * @zonelist - The zonelist to search for a suitable zone * @highest_zoneidx - The zone index of the highest zone to return * @nodes - An optional nodemask to filter the zonelist with * @zone - The first suitable zone found is returned via this parameter * * This function returns the first zone at or below a given zone index that is * within the allowed nodemask. The zoneref returned is a cursor that can be * used to iterate the zonelist with next_zones_zonelist by advancing it by * one before calling. */ static inline struct zoneref *<API key>(struct zonelist *zonelist, enum zone_type highest_zoneidx, nodemask_t *nodes, struct zone **zone) { return next_zones_zonelist(zonelist->_zonerefs, highest_zoneidx, nodes, zone); } /** * <API key> - helper macro to iterate over valid zones in a zonelist at or below a given zone index and within a nodemask * @zone - The current zone in the iterator * @z - The current pointer within zonelist->zones being iterated * @zlist - The zonelist being iterated * @highidx - The zone index of the highest zone to return * @nodemask - Nodemask allowed by the allocator * * This iterator iterates though all zones at or below a given zone index and * within a given nodemask */ #define <API key>(zone, z, zlist, highidx, nodemask) \ for (z = <API key>(zlist, highidx, nodemask, &zone); \ zone; \ z = next_zones_zonelist(++z, highidx, nodemask, &zone)) \ /** * <API key> - helper macro to iterate over valid zones in a zonelist at or below a given zone index * @zone - The current zone in the iterator * @z - The current pointer within zonelist->zones being iterated * @zlist - The zonelist being iterated * @highidx - The zone index of the highest zone to return * * This iterator iterates though all zones at or below a given zone index. */ #define <API key>(zone, z, zlist, highidx) \ <API key>(zone, z, zlist, highidx, NULL) #ifdef CONFIG_SPARSEMEM #include <asm/sparsemem.h> #endif #if !defined(<API key>) && \ !defined(<API key>) static inline unsigned long early_pfn_to_nid(unsigned long pfn) { return 0; } #endif #ifdef CONFIG_FLATMEM #define pfn_to_nid(pfn) (0) #endif #ifdef CONFIG_SPARSEMEM /* * SECTION_SHIFT #bits space required to store a section # * * PA_SECTION_SHIFT physical address to/from section number * PFN_SECTION_SHIFT pfn to/from section number */ #define SECTIONS_SHIFT (MAX_PHYSMEM_BITS - SECTION_SIZE_BITS) #define PA_SECTION_SHIFT (SECTION_SIZE_BITS) #define PFN_SECTION_SHIFT (SECTION_SIZE_BITS - PAGE_SHIFT) #define NR_MEM_SECTIONS (1UL << SECTIONS_SHIFT) #define PAGES_PER_SECTION (1UL << PFN_SECTION_SHIFT) #define PAGE_SECTION_MASK (~(PAGES_PER_SECTION-1)) #define <API key> \ ((1UL << (PFN_SECTION_SHIFT - pageblock_order)) * NR_PAGEBLOCK_BITS) #if (MAX_ORDER - 1 + PAGE_SHIFT) > SECTION_SIZE_BITS #error Allocator MAX_ORDER exceeds SECTION_SIZE #endif #define pfn_to_section_nr(pfn) ((pfn) >> PFN_SECTION_SHIFT) #define section_nr_to_pfn(sec) ((sec) << PFN_SECTION_SHIFT) #define SECTION_ALIGN_UP(pfn) (((pfn) + PAGES_PER_SECTION - 1) & PAGE_SECTION_MASK) #define SECTION_ALIGN_DOWN(pfn) ((pfn) & PAGE_SECTION_MASK) struct page; struct page_cgroup; struct mem_section { /* * This is, logically, a pointer to an array of struct * pages. However, it is stored with some other magic. * (see sparse.c::<API key>()) * * Additionally during early boot we encode node id of * the location of the section here to guide allocation. * (see sparse.c::memory_present()) * * Making it a UL at least makes someone do a cast * before using it wrong. */ unsigned long section_mem_map; /* See declaration of similar field in struct zone */ unsigned long *pageblock_flags; #ifdef <API key> /* * If !SPARSEMEM, pgdat doesn't have page_cgroup pointer. We use * section. (see memcontrol.h/page_cgroup.h about this.) */ struct page_cgroup *page_cgroup; unsigned long pad; #endif }; #ifdef <API key> #define SECTIONS_PER_ROOT (PAGE_SIZE / sizeof (struct mem_section)) #else #define SECTIONS_PER_ROOT 1 #endif #define SECTION_NR_TO_ROOT(sec) ((sec) / SECTIONS_PER_ROOT) #define NR_SECTION_ROOTS DIV_ROUND_UP(NR_MEM_SECTIONS, SECTIONS_PER_ROOT) #define SECTION_ROOT_MASK (SECTIONS_PER_ROOT - 1) #ifdef <API key> extern struct mem_section *mem_section[NR_SECTION_ROOTS]; #else extern struct mem_section mem_section[NR_SECTION_ROOTS][SECTIONS_PER_ROOT]; #endif static inline struct mem_section *__nr_to_section(unsigned long nr) { if (!mem_section[SECTION_NR_TO_ROOT(nr)]) return NULL; return &mem_section[SECTION_NR_TO_ROOT(nr)][nr & SECTION_ROOT_MASK]; } extern int __section_nr(struct mem_section* ms); extern unsigned long usemap_size(void); /* * We use the lower bits of the mem_map pointer to store * a little bit of information. There should be at least * 3 bits here due to 32-bit alignment. */ #define <API key> (1UL<<0) #define SECTION_HAS_MEM_MAP (1UL<<1) #define <API key> (1UL<<2) #define SECTION_MAP_MASK (~(<API key>)) #define SECTION_NID_SHIFT 2 static inline struct page *<API key>(struct mem_section *section) { unsigned long map = section->section_mem_map; map &= SECTION_MAP_MASK; return (struct page *)map; } static inline int present_section(struct mem_section *section) { return (section && (section->section_mem_map & <API key>)); } static inline int present_section_nr(unsigned long nr) { return present_section(__nr_to_section(nr)); } static inline int valid_section(struct mem_section *section) { return (section && (section->section_mem_map & SECTION_HAS_MEM_MAP)); } static inline int valid_section_nr(unsigned long nr) { return valid_section(__nr_to_section(nr)); } static inline struct mem_section *__pfn_to_section(unsigned long pfn) { return __nr_to_section(pfn_to_section_nr(pfn)); } #ifndef <API key> static inline int pfn_valid(unsigned long pfn) { if (pfn_to_section_nr(pfn) >= NR_MEM_SECTIONS) return 0; return valid_section(__nr_to_section(pfn_to_section_nr(pfn))); } #endif static inline int pfn_present(unsigned long pfn) { if (pfn_to_section_nr(pfn) >= NR_MEM_SECTIONS) return 0; return present_section(__nr_to_section(pfn_to_section_nr(pfn))); } /* * These are _only_ used during initialisation, therefore they * can use __initdata ... They could have names to indicate * this restriction. */ #ifdef CONFIG_NUMA #define pfn_to_nid(pfn) \ ({ \ unsigned long __pfn_to_nid_pfn = (pfn); \ page_to_nid(pfn_to_page(__pfn_to_nid_pfn)); \ }) #else #define pfn_to_nid(pfn) (0) #endif #define early_pfn_valid(pfn) pfn_valid(pfn) void sparse_init(void); #else #define sparse_init() do {} while (0) #define sparse_index_init(_sec, _nid) do {} while (0) #endif /* CONFIG_SPARSEMEM */ #ifdef <API key> bool early_pfn_in_nid(unsigned long pfn, int nid); #else #define early_pfn_in_nid(pfn, nid) (1) #endif #ifndef early_pfn_valid #define early_pfn_valid(pfn) (1) #endif void memory_present(int nid, unsigned long start, unsigned long end); unsigned long __init <API key>(int, unsigned long, unsigned long); /* * If it is possible to have holes within a MAX_ORDER_NR_PAGES, then we * need to check pfn validility within that MAX_ORDER_NR_PAGES block. * pfn_valid_within() should be used in this case; we optimise this away * when we have no holes within a MAX_ORDER_NR_PAGES block. */ #ifdef <API key> #define pfn_valid_within(pfn) pfn_valid(pfn) #else #define pfn_valid_within(pfn) (1) #endif #ifdef <API key> /* * pfn_valid() is meant to be able to tell if a given PFN has valid memmap * associated with it or not. In FLATMEM, it is expected that holes always * have valid memmap as long as there is valid PFNs either side of the hole. * In SPARSEMEM, it is assumed that a valid section has a memmap for the * entire section. * * However, an ARM, and maybe other embedded architectures in the future * free memmap backing holes to save memory on the assumption the memmap is * never used. The page_zone linkages are then broken even though pfn_valid() * returns true. A walker of the full memmap must then do this additional * check to ensure the memmap they are looking at is sane by making sure * the zone and PFN linkages are still valid. This is expensive, but walkers * of the full memmap are extremely rare. */ int memmap_valid_within(unsigned long pfn, struct page *page, struct zone *zone); #else static inline int memmap_valid_within(unsigned long pfn, struct page *page, struct zone *zone) { return 1; } #endif /* <API key> */ #endif /* !__GENERATING_BOUNDS.H */ #endif /* !__ASSEMBLY__ */ #endif /* _LINUX_MMZONE_H */
layout: post title: 'Podcast: What Is the Technical Writer''s Role in Interface Design? Interview with Bogo Vatovec' date: 2008-12-14 18:06:40.000000000 -08:00 categories: - podcasts tags: [] status: publish published: true <p><audio controls><source src="https: <p><a title="What Is the Technical Writer's Role in Interface Design?" href="https: Duration: 38 min.</p> <p>In this podcast, I interview Bogo Vatovec, an expert in change management, user experience, and knowledge engineering, about the technical writer's role in interface design. Specifically, we cover the following in the podcast:</p> <p></p> <ul> <li>What the technical writer's role should be in the company</li> <li>Why the technical writer's skills are often "accepted but not respected"</li> <li>Why a technical writer needs to do more than just what he or she is told </li> <li>What the technical writer's role is in relation to design and usability</li> <li>The importance of spinning your criticisms of prototypes in positive ways</li> <li>How early the technical writer should get involved with a project</li> <li>The semantics and implications of names ("technical writer" versus "information designer")</li> <li>How the role of an information designer differs from the role of a technical writer</li> <li>Why changing the name from "writer" to some other title isn't enough</li> <li>Why writing skills are a declining value</li> <li>What happens when writers do more</li> </ul> <p>Bogo is a senior member of the STC and a regular presenter at conferences worldwide. For example, at the last STC Summit, Bogo participated in a panel on career trends.</p> <p>For more information on Bogo Vatovec, see his site at <a href="http://bovacon.com" target="_blank">bovacon.com</a>. </p>
require 'socket' require 'ssh/ruby_compat' require 'ssh/proxy/errors' module Net module SSH module Proxy # An implementation of a SOCKS5 proxy. To use it, instantiate it, then # pass the instantiated object via the :proxy key to Net::SSH.start: # require 'ssh/proxy/socks5' # proxy = Net::SSH::Proxy::SOCKS5.new('proxy.host', proxy_port, # :user => 'user', :password => "password") # Net::SSH.start('host', 'user', :proxy => proxy) do |ssh| # end class SOCKS5 # The SOCKS protocol version used by this class VERSION = 5 # The SOCKS authentication type for requests without authentication METHOD_NO_AUTH = 0 # The SOCKS authentication type for requests via username/password METHOD_PASSWD = 2 # The SOCKS authentication type for when there are no supported # authentication methods. METHOD_NONE = 0xFF # The SOCKS packet type for requesting a proxy connection. CMD_CONNECT = 1 # The SOCKS address type for connections via IP address. ATYP_IPV4 = 1 # The SOCKS address type for connections via domain name. ATYP_DOMAIN = 3 # The SOCKS response code for a successful operation. SUCCESS = 0 # The proxy's host name or IP address attr_reader :proxy_host # The proxy's port number attr_reader :proxy_port # The map of options given at initialization attr_reader :options # Create a new proxy connection to the given proxy host and port. # Optionally, :user and :password options may be given to # identify the username and password with which to authenticate. def initialize(proxy_host, proxy_port=1080, options={}) @proxy_host = proxy_host @proxy_port = proxy_port @options = options end # Return a new socket connected to the given host and port via the # proxy that was requested when the socket factory was instantiated. def open(host, port) socket = TCPSocket.new(proxy_host, proxy_port) methods = [METHOD_NO_AUTH] methods << METHOD_PASSWD if options[:user] packet = [VERSION, methods.size, *methods].pack("C*") socket.send packet, 0 version, method = socket.recv(2).unpack("CC") if version != VERSION socket.close raise Net::SSH::Proxy::Error, "invalid SOCKS version (#{version})" end if method == METHOD_NONE socket.close raise Net::SSH::Proxy::Error, "no supported authorization methods" end negotiate_password(socket) if method == METHOD_PASSWD packet = [VERSION, CMD_CONNECT, 0].pack("C*") if host =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/ packet << [ATYP_IPV4, $1.to_i, $2.to_i, $3.to_i, $4.to_i].pack("C*") else packet << [ATYP_DOMAIN, host.length, host].pack("CCA*") end packet << [port].pack("n") socket.send packet, 0 version, reply, = socket.recv(2).unpack("C*") socket.recv(1) address_type = socket.recv(1).getbyte(0) case address_type when 1 socket.recv(4) # get four bytes for IPv4 address when 3 len = socket.recv(1).getbyte(0) hostname = socket.recv(len) when 4 ipv6addr hostname = socket.recv(16) else socket.close raise ConnectionError, "Illegal response type" end portnum = socket.recv(2) unless reply == SUCCESS socket.close raise ConnectError, "#{reply}" end return socket end private # Simple username/password negotiation with the SOCKS5 server. def negotiate_password(socket) packet = [0x01, options[:user].length, options[:user], options[:password].length, options[:password]].pack("CCA*CA*") socket.send packet, 0 version, status = socket.recv(2).unpack("CC") if status != SUCCESS socket.close raise UnauthorizedError, "could not authorize user" end end end end end end
package org.drftpd.master.vfs.event; import org.drftpd.master.vfs.<API key>; import java.util.Set; /** * This event is fired whenever a slave is added or removed from a {@link <API key>} * * @author fr0w * @version $Id$ */ public class <API key> extends <API key> { private final Set<String> _slaves; public <API key>(<API key> file, String path, Set<String> slaves) { super(file, path); _slaves = slaves; } /** * @return the new set of Slaves */ public Set<String> getSlaves() { return _slaves; } }
package eu.printingin3d.javascad.models; import eu.printingin3d.javascad.basic.Radius; import eu.printingin3d.javascad.context.<API key>; import eu.printingin3d.javascad.exceptions.<API key>; import eu.printingin3d.javascad.utils.AssertValue; import eu.printingin3d.javascad.utils.DoubleUtils; /** * Represents a prism or a pyramid. * It is a descendant of Abstract3dModel, * which means you can use the convenient methods on prisms too. * * @author ivivan <ivivan@printingin3d.eu> */ public class Prism extends Cylinder { private final int numberOfSides; /** * Creates a prism with a given length, radius and the number of sides. * @param length the length of the prism * @param r the radius of the prism * @param numberOfSides the side number of the prism * @throws <API key> if any of its parameters is negative */ public Prism(double length, Radius r, int numberOfSides) throws <API key> { super(length, r); AssertValue.isNotNegative(numberOfSides, "The number of sides should be positive, but "+numberOfSides); this.numberOfSides = numberOfSides; } /** * Creates a prism, which base and top have different radius. * If one of the two radiuses is zero the result is a pyramid. * If the two radiuses are the same the result is the same as {@link #Prism(double, double, int)}. * @param length the length of the prism * @param r1 the bottom radius of the prism * @param r2 the top radius of the prism * @param numberOfSides the side number of the prism * @throws <API key> if any of its parameters is negative */ public Prism(double length, Radius r1, Radius r2, int numberOfSides) throws <API key> { super(length, r1, r2); AssertValue.isNotNegative(numberOfSides, "The number of sides should be positive, but "+numberOfSides); this.numberOfSides = numberOfSides; } /** * Creates a prism with a given length, radius and the number of sides. * @param length the length of the prism * @param r the radius of the prism * @param numberOfSides the side number of the prism * @throws <API key> if any of its parameters is negative * @deprecated use the constructor with Radius parameters instead of doubles */ @Deprecated public Prism(double length, double r, int numberOfSides) throws <API key> { this(length, Radius.fromRadius(r), numberOfSides); } /** * Creates a prism, which base and top have different radius. * If one of the two radiuses is zero the result is a pyramid. * If the two radiuses are the same the result is the same as {@link #Prism(double, double, int)}. * @param length the length of the prism * @param r1 the bottom radius of the prism * @param r2 the top radius of the prism * @param numberOfSides the side number of the prism * @throws <API key> if any of its parameters is negative * @deprecated use the constructor with Radius parameters instead of doubles */ @Deprecated public Prism(double length, double r1, double r2, int numberOfSides) throws <API key> { this(length, Radius.fromRadius(r1), Radius.fromRadius(r2), numberOfSides); } @Override protected SCAD innerToScad(<API key> context) { if (bottomRadius.equals(topRadius)) { return new SCAD("cylinder(h="+DoubleUtils.formatDouble(length)+ ", r="+bottomRadius+ ", $fn="+numberOfSides+", center=true);\n"); } return new SCAD("cylinder(h="+DoubleUtils.formatDouble(length)+ ", r1="+bottomRadius+ ", r2="+topRadius+ ", $fn="+numberOfSides+", center=true);\n"); } @Override protected Abstract3dModel innerCloneModel() { return new Prism(length, bottomRadius, topRadius, numberOfSides); } }
<?php $type = 'TrueType'; $name = 'Verdana'; $desc = array('Ascent'=>765,'Descent'=>-207,'CapHeight'=>765,'Flags'=>32,'FontBBox'=>'[-50 -207 1447 1000]','ItalicAngle'=>0,'StemV'=>70,'MissingWidth'=>1000); $up = -88; $ut = 59; $cw = array( chr(0)=>1000,chr(1)=>1000,chr(2)=>1000,chr(3)=>1000,chr(4)=>1000,chr(5)=>1000,chr(6)=>1000,chr(7)=>1000,chr(8)=>1000,chr(9)=>1000,chr(10)=>1000,chr(11)=>1000,chr(12)=>1000,chr(13)=>1000,chr(14)=>1000,chr(15)=>1000,chr(16)=>1000,chr(17)=>1000,chr(18)=>1000,chr(19)=>1000,chr(20)=>1000,chr(21)=>1000, chr(22)=>1000,chr(23)=>1000,chr(24)=>1000,chr(25)=>1000,chr(26)=>1000,chr(27)=>1000,chr(28)=>1000,chr(29)=>1000,chr(30)=>1000,chr(31)=>1000,' '=>352,'!'=>394,'"'=>459,'#'=>818,'$'=>636,'%'=>1076,'&'=>727,'\''=>269,'('=>454,')'=>454,'*'=>636,'+'=>818, ','=>364,'-'=>454,'.'=>364,'/'=>454,'0'=>636,'1'=>636,'2'=>636,'3'=>636,'4'=>636,'5'=>636,'6'=>636,'7'=>636,'8'=>636,'9'=>636,':'=>454,';'=>454,'<'=>818,'='=>818,'>'=>818,'?'=>545,'@'=>1000,'A'=>684, 'B'=>686,'C'=>698,'D'=>771,'E'=>632,'F'=>575,'G'=>775,'H'=>751,'I'=>421,'J'=>455,'K'=>693,'L'=>557,'M'=>843,'N'=>748,'O'=>787,'P'=>603,'Q'=>787,'R'=>695,'S'=>684,'T'=>616,'U'=>732,'V'=>684,'W'=>989, 'X'=>685,'Y'=>615,'Z'=>685,'['=>454,'\\'=>454,']'=>454,'^'=>818,'_'=>636,'`'=>636,'a'=>601,'b'=>623,'c'=>521,'d'=>623,'e'=>596,'f'=>352,'g'=>623,'h'=>633,'i'=>274,'j'=>344,'k'=>592,'l'=>274,'m'=>973, 'n'=>633,'o'=>607,'p'=>623,'q'=>623,'r'=>427,'s'=>521,'t'=>394,'u'=>633,'v'=>592,'w'=>818,'x'=>592,'y'=>592,'z'=>525,'{'=>635,'|'=>454,'}'=>635,'~'=>818,chr(127)=>1000,chr(128)=>636,chr(129)=>1000,chr(130)=>269,chr(131)=>636, chr(132)=>459,chr(133)=>818,chr(134)=>636,chr(135)=>636,chr(136)=>636,chr(137)=>1521,chr(138)=>684,chr(139)=>454,chr(140)=>1070,chr(141)=>1000,chr(142)=>685,chr(143)=>1000,chr(144)=>1000,chr(145)=>269,chr(146)=>269,chr(147)=>459,chr(148)=>459,chr(149)=>545,chr(150)=>636,chr(151)=>1000,chr(152)=>636,chr(153)=>977, chr(154)=>521,chr(155)=>454,chr(156)=>981,chr(157)=>1000,chr(158)=>525,chr(159)=>615,chr(160)=>352,chr(161)=>394,chr(162)=>636,chr(163)=>636,chr(164)=>636,chr(165)=>636,chr(166)=>454,chr(167)=>636,chr(168)=>636,chr(169)=>1000,chr(170)=>545,chr(171)=>645,chr(172)=>818,chr(173)=>454,chr(174)=>1000,chr(175)=>636, chr(176)=>542,chr(177)=>818,chr(178)=>542,chr(179)=>542,chr(180)=>636,chr(181)=>642,chr(182)=>636,chr(183)=>364,chr(184)=>636,chr(185)=>542,chr(186)=>545,chr(187)=>645,chr(188)=>1000,chr(189)=>1000,chr(190)=>1000,chr(191)=>545,chr(192)=>684,chr(193)=>684,chr(194)=>684,chr(195)=>684,chr(196)=>684,chr(197)=>684, chr(198)=>984,chr(199)=>698,chr(200)=>632,chr(201)=>632,chr(202)=>632,chr(203)=>632,chr(204)=>421,chr(205)=>421,chr(206)=>421,chr(207)=>421,chr(208)=>775,chr(209)=>748,chr(210)=>787,chr(211)=>787,chr(212)=>787,chr(213)=>787,chr(214)=>787,chr(215)=>818,chr(216)=>787,chr(217)=>732,chr(218)=>732,chr(219)=>732, chr(220)=>732,chr(221)=>615,chr(222)=>605,chr(223)=>620,chr(224)=>601,chr(225)=>601,chr(226)=>601,chr(227)=>601,chr(228)=>601,chr(229)=>601,chr(230)=>955,chr(231)=>521,chr(232)=>596,chr(233)=>596,chr(234)=>596,chr(235)=>596,chr(236)=>274,chr(237)=>274,chr(238)=>274,chr(239)=>274,chr(240)=>612,chr(241)=>633, chr(242)=>607,chr(243)=>607,chr(244)=>607,chr(245)=>607,chr(246)=>607,chr(247)=>818,chr(248)=>607,chr(249)=>633,chr(250)=>633,chr(251)=>633,chr(252)=>633,chr(253)=>592,chr(254)=>623,chr(255)=>592); $enc = 'cp1252'; $file = 'verdana.z'; $originalsize = 171792; ?>
package com.espertech.esper.epl.spec; import com.espertech.esper.collection.Pair; import com.espertech.esper.epl.expression.<API key>; import com.espertech.esper.epl.parse.EPLTreeWalker; import com.espertech.esper.filter.*; import com.espertech.esper.pattern.<API key>; import com.espertech.esper.pattern.<API key>; import com.espertech.esper.pattern.EvalNodeUtil; import com.espertech.esper.support.bean.SupportBean; import com.espertech.esper.support.epl.parse.<API key>; import com.espertech.esper.support.epl.parse.SupportParserHelper; import com.espertech.esper.support.view.<API key>; import junit.framework.TestCase; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.tree.Tree; import java.util.Collections; import java.util.HashSet; import java.util.List; public class <API key> extends TestCase { public void testPatternEquals() throws Exception { String text = "select * from pattern [" + "s=" + SupportBean.class.getName() + "(intPrimitive=5) -> " + "t=" + SupportBean.class.getName() + "(intPrimitive=s.intBoxed)" + "]"; tryPatternEquals(text); text = "select * from pattern [" + "s=" + SupportBean.class.getName() + "(5=intPrimitive) -> " + "t=" + SupportBean.class.getName() + "(s.intBoxed=intPrimitive)" + "]"; tryPatternEquals(text); } public void testInvalid() throws Exception { String text = "select * from pattern [" + "s=" + SupportBean.class.getName() + " -> " + "t=" + SupportBean.class.getName() + "(intPrimitive=s.doubleBoxed)" + "]"; tryInvalid(text); text = "select * from pattern [" + "s=" + SupportBean.class.getName() + " -> " + "t=" + SupportBean.class.getName() + "(intPrimitive in (s.doubleBoxed))" + "]"; tryInvalid(text); } private void tryInvalid(String text) throws Exception { try { <API key> raw = makeSpec(text); compile(raw); fail(); } catch (<API key> ex) { // expected } } public void <API key>() throws Exception { String text = "select * from pattern [" + "s=" + SupportBean.class.getName() + "(intPrimitive in (s.intBoxed + 1, 0), intBoxed+1=intPrimitive-1)" + "]"; <API key> raw = makeSpec(text); <API key> spec = compile(raw); assertEquals(1, spec.getTaggedEventTypes().size()); assertEquals(SupportBean.class, spec.getTaggedEventTypes().get("s").getFirst().getUnderlyingType()); <API key> <API key> = EvalNodeUtil.<API key>(spec.getEvalFactoryNode()); List<<API key>> filters = <API key>.getFilterNodes(); assertEquals(1, filters.size()); // node 0 <API key> filterNode = filters.get(0); assertEquals(SupportBean.class, filterNode.getFilterSpec().<API key>().getUnderlyingType()); assertEquals(1, filterNode.getFilterSpec().getParameters().length); <API key> exprParam = (<API key>) filterNode.getFilterSpec().getParameters()[0]; } public void <API key>() throws Exception { String text = "select * from pattern [" + "s=" + SupportBean.class.getName() + " -> " + SupportBean.class.getName() + "(intPrimitive in (s.intBoxed, 0))" + "]"; <API key> raw = makeSpec(text); <API key> spec = compile(raw); assertEquals(1, spec.getTaggedEventTypes().size()); assertEquals(SupportBean.class, spec.getTaggedEventTypes().get("s").getFirst().getUnderlyingType()); <API key> <API key> = EvalNodeUtil.<API key>(spec.getEvalFactoryNode()); List<<API key>> filters = <API key>.getFilterNodes(); assertEquals(2, filters.size()); // node 0 <API key> filterNode = filters.get(0); assertEquals(SupportBean.class, filterNode.getFilterSpec().<API key>().getUnderlyingType()); assertEquals(0, filterNode.getFilterSpec().getParameters().length); // node 1 filterNode = filters.get(1); assertEquals(SupportBean.class, filterNode.getFilterSpec().<API key>().getUnderlyingType()); assertEquals(1, filterNode.getFilterSpec().getParameters().length); FilterSpecParamIn inlist = (FilterSpecParamIn) filterNode.getFilterSpec().getParameters()[0]; assertEquals(FilterOperator.IN_LIST_OF_VALUES, inlist.getFilterOperator()); assertEquals(2, inlist.getListOfValues().size()); // in-value 1 <API key> prop = (<API key>) inlist.getListOfValues().get(0); assertEquals("s", prop.<API key>()); assertEquals("intBoxed", prop.<API key>()); // in-value 1 <API key> constant = (<API key>) inlist.getListOfValues().get(1); assertEquals(0, constant.getConstant()); } public void testRange() throws Exception { String text = "select * from pattern [" + "s=" + SupportBean.class.getName() + " -> " + SupportBean.class.getName() + "(intPrimitive between s.intBoxed and 100)" + "]"; <API key> raw = makeSpec(text); <API key> spec = compile(raw); assertEquals(1, spec.getTaggedEventTypes().size()); assertEquals(SupportBean.class, spec.getTaggedEventTypes().get("s").getFirst().getUnderlyingType()); <API key> <API key> = EvalNodeUtil.<API key>(spec.getEvalFactoryNode()); List<<API key>> filters = <API key>.getFilterNodes(); assertEquals(2, filters.size()); // node 0 <API key> filterNode = filters.get(0); assertEquals(SupportBean.class, filterNode.getFilterSpec().<API key>().getUnderlyingType()); assertEquals(0, filterNode.getFilterSpec().getParameters().length); // node 1 filterNode = filters.get(1); assertEquals(SupportBean.class, filterNode.getFilterSpec().<API key>().getUnderlyingType()); assertEquals(1, filterNode.getFilterSpec().getParameters().length); <API key> range = (<API key>) filterNode.getFilterSpec().getParameters()[0]; assertEquals(FilterOperator.RANGE_CLOSED, range.getFilterOperator()); // min-value RangeValueEventProp prop = (RangeValueEventProp) range.getMin(); assertEquals("s", prop.<API key>()); assertEquals("intBoxed", prop.<API key>()); // max-value RangeValueDouble constant = (RangeValueDouble) range.getMax(); assertEquals(100d, constant.getDoubleValue()); } private void tryPatternEquals(String text) throws Exception { <API key> raw = makeSpec(text); <API key> spec = compile(raw); assertEquals(2, spec.getTaggedEventTypes().size()); assertEquals(SupportBean.class, spec.getTaggedEventTypes().get("s").getFirst().getUnderlyingType()); assertEquals(SupportBean.class, spec.getTaggedEventTypes().get("t").getFirst().getUnderlyingType()); <API key> <API key> = EvalNodeUtil.<API key>(spec.getEvalFactoryNode()); List<<API key>> filters = <API key>.getFilterNodes(); assertEquals(2, filters.size()); // node 0 <API key> filterNode = filters.get(0); assertEquals(SupportBean.class, filterNode.getFilterSpec().<API key>().getUnderlyingType()); assertEquals(1, filterNode.getFilterSpec().getParameters().length); <API key> constant = (<API key>) filterNode.getFilterSpec().getParameters()[0]; assertEquals(FilterOperator.EQUAL, constant.getFilterOperator()); assertEquals("intPrimitive", constant.getLookupable().getExpression()); assertEquals(5, constant.getFilterConstant()); // node 1 filterNode = filters.get(1); assertEquals(SupportBean.class, filterNode.getFilterSpec().<API key>().getUnderlyingType()); assertEquals(1, filterNode.getFilterSpec().getParameters().length); <API key> eventprop = (<API key>) filterNode.getFilterSpec().getParameters()[0]; assertEquals(FilterOperator.EQUAL, constant.getFilterOperator()); assertEquals("intPrimitive", constant.getLookupable().getExpression()); assertEquals("s", eventprop.<API key>()); assertEquals("intBoxed", eventprop.<API key>()); } private <API key> compile(<API key> raw) throws Exception { return raw.compile(<API key>.makeContext(), new HashSet<String>(), false, Collections.<Integer>emptyList()); } private static <API key> makeSpec(String expression) throws Exception { Pair<Tree, CommonTokenStream> ast = SupportParserHelper.parseEPL(expression); SupportParserHelper.displayAST(ast.getFirst()); EPLTreeWalker walker = <API key>.makeWalker(ast.getFirst(), ast.getSecond()); walker.<API key>(); <API key> spec = (<API key>) walker.getStatementSpec().getStreamSpecs().get(0); return spec; } }
\chap{Preliminaries}{BeforeWeBegin} \section{In the Beginning} \begin{verse} Let's start at the very beginning\\ A very good place to start\\ When you read you begin with A B C\\ When you sing you begin with Do Re Me \end{verse} \medskip (Oscar Hammerstein, \emph{The Sound of Music}) \bigskip If Maria had been the Trapp children's math tutor, she might have continued: ``When you count, you begin with 1 2 3''. Ordinarily we think of the ``counting numbers'' (which mathematicians call the \emph{natural numbers} or \emph{positive integers}) as the ``very beginning'' of math.\footnote{A famous mathematician once said, ``God made the integers; all else is the work of man.'' (Leopold Kronecker, German mathematician, 1886)} \medskip It's true that when we learn math in school, we begin with the counting numbers. But do we really start at the ``very beginning''? How do we know that $1 + 1 = 2$? How do we know that the methods we learned to add, multiply, divide, and subtract will always work? We've been taught how to factor integers into prime factors. But how do we know this always works? Mathematicians are the ultimate skeptics: they won't take ``Everyone knows'' or ``It's obvious'' as valid reasons. They keep asking ``why'', breaking things down into the most basic assumptions possible. The very basic assumptions they end up with are called \term{axioms}\index{Axiom}. They then take these axioms and play with them like building blocks. The arguments that they build with these axioms are called \term{proofs}, and the conclusions of these proofs are called \term{propositions}\index{Proposition!mathematical} or \term{theorems}\index{Theorem}. The mathematician's path is not an easy one. It is exceedingly difficult to push things back to their foundations. For example, arithmetic was used for thousands of years before a set of simple axioms was finally developed (you may look up ``Peano axioms'' on the web).\footnote{The same is true for calculus. Newton and Leibniz first developed calculus around 1670, but it wasn't made rigorous until 150 years later.} Since this is an elementary book, we are not going to try to meet rigorous mathematical standards. Instead, we'll lean heavily on examples, including the integers, rationals, and real numbers. Once you are really proficient with different examples, then it will be easier to follow more advanced ideas.\footnote{Historically, mathematics has usually progressed this way: examples first, and axioms later after the examples are well-understood.} This text is loaded with proofs, which are as unavoidable in abstract mathematics as they are intimidating to many students. We try to ``tone things down'' as much as possible. For example, we will take as ``fact'' many of the things that you learned in high school and college algebra--even though you've never seen proofs of these ``facts''. In the next section we remind you of some of these ``facts''. When writing proofs or doing exercise feel free to use any of these facts. If you have to give a reason, you can just say ``basic algebra''.\index{Algebra!high school and college} We close this prologue with the assurance that abstract algebra is a beautiful subject that brings amazing insights into the nature of numbers, and the nature of Nature itself. Furthermore, engineers and technologists are finding more and more practical applications, as we shall see in the coming chapters. \section {Integers, rational numbers, real numbers} We assume that you have already been introduced to the following number systems: integers, rational numbers, and real numbers.\footnote{The original versions of this section and the next were written by David Weathers.} These number systems possess the well-known arithmetic operations of addition, subtraction, multiplication, and division. The following statements hold for all of these number systems. \begin{warn} There are number systems for which the following properties do NOT hold (as we shall see later). So they may be safely assumed ONLY for integers, rational numbers, and real numbers. \end{warn} \subsection{Operations and relations }\label{OpsAndRels} We assume the following properties of these arithmetic operations: \begin{enumerate}[(a)] \item \term{Commutative}\index{Commutative!in ordinary arithmetic}: When two numbers are added together, the two numbers can be exchanged without changing the value of the result. The same thing is true for two numbers being mulitiplied together. \item \term{Associative}\index{Associative!in ordinary arithmetic}: When three or more numbers are added together, changing the grouping of the numbers being added does not change the value of the result. The same goes for three or more numbers multiplied together. (Note that in arithmetic expressions, the ``grouping'' of numbers is indicated by parentheses.) \item \term{Distributive}\index{Distributive!in ordinary arithmetic}: Multiplying a number by a sum gives the same result as taking the sum of the products. \item \term{Order}: Given two numbers, exactly one of these three are true: either the first number is greater than the second, or the second number is greater than the first, or the two numbers are equal. \item \term{Identity}\index{Identity!in ordinary arithmetic}: Addition by 0 or multiplication by 1 result in no change of original number. \item The sum of two positive numbers is positive. The sum of two negative numbers is negative. \item The product of two nonzero numbers with the same sign is positive. The product of two numbers with different signs is negative. \item If the product of two numbers is zero, then one or the other number must be zero. \end {enumerate} \begin{exercise}{1} \begin{enumerate}[(a)] \item For the properties a,b,c,e above, give (i) a specific example for addition, using numbers, and (ii) a general statement for multiplication, using variables. For example, for property (a) (the commutative property) a specific example would be $3+5 = 5+3$, and a general statement would be $x \cdot y=y \cdot x$. \item For properties d,f,g,h above, give a specific example which illustrates the property using numbers. \end{enumerate} \end{exercise} \begin{exercise}{2} \begin{enumerate}[(a)] \item Give an example (using numbers) that shows that subtraction is \emph{not} commutative .\item Give an example (using numbers) that shows that division is \emph{not} associative. \end{enumerate} \end{exercise} \begin{exercise}{3} Suppose $a > b$, $b \ge 0$ and $ab = 0$. What can you conclude about $a$ and $b$? Use one (or more) of the properties we have mentioned to justify your answer. \end{exercise} \begin{exercise}{} Which of the above properties must be used to prove each of the following statements? \begin{enumerate}[(a)] \item $(x+y)+(z+w) = (z+w)+(x+y)$ \item $(x \cdot y) \cdot z = ( z \cdot x) \cdot y$ \item $(a\cdot x + a \cdot y) + a \cdot z = a \cdot ( (x+y) + z)$ \item $((a \cdot b) \cdot c + b \cdot c) + c \cdot a = c \cdot ((a+b) + a \cdot b)$ \end{enumerate} \end{exercise} Note that the associative property allows us to write expressions without putting in so many parentheses. So instead of writing $(a+b)+c$, we may simply write $a+b+c$. By the same reasoning, we can remove parentheses from any expression that involves only addition, or any expression that involves only multiplication: so for instance, $(a \cdot (b \cdot c) \cdot d) \cdot e = a \cdot b \cdot c \cdot d \cdots e$. Using the associative and distributive property, it is possible to write any arithmetic expression without parentheses. So for example, $(a \cdot b) \cdot (c + d)$ can be written as $a \cdot b \cdot c + a \cdot b \cdot d$. (Remember that according to operator precedence rules, multiplication is always performed before addition: thus $3 \cdot 4 + 2$ is evaluated by first taking $3 \cdot 4$ and then adding 2.) \begin{exercise}{} Rewrite the following expressions without any parentheses, using \emph{only} the associative and distributive properties. ({\underline Don't use commutative in this exercise!}) \begin{enumerate}[(a)] \item $(((x + y) + (y+z))\cdot w) - 2y \cdot w$ \item $0.5 \cdot ( (x+y) + (y + z) + (z + x))$ \item $((((((a+b)+c) \cdot d)+ e) \cdot f) + g) + h$ \end{enumerate} \end{exercise} \begin{exercise}{} For parts (a--c) of the preceding exercise, now apply the commutative property to the results to simplify the expressions as much as possible. \end{exercise} \begin{exercise}{} Evaluate the following expressions by hand (no calculators!). \begin{enumerate}[(a)] \item $3 \cdot 4 + 5 + 6 \cdot 2$ \item $3 + 4 \cdot 5 \cdot 6 + 2$ \item $1 + 2 \cdot 3 + 3 \cdot 4 \cdot 5 + 5 \cdot 6 \cdot 7 \cdot 2$ \end{enumerate} \end{exercise} \subsection {Manipulating equations and inequalities}\label{subsec:eqsAndIneqs} Following are some common rules for manipulating equations and inequalities. Notice there are two types of inequalities: \term{strict inequalities} (that use the $>$ or $<$ symbols) and \term{nonstrict inequalities} (that use the $\ge$ or $\le$ symbols).\index{Inequality!strict}\index{Inequality!nonstrict} \begin {enumerate}[(A)] \item \emph{Substitution}: If two quantities are equal then one can be substituted for the other in any true equation or inequality and the result will still be true. \item \emph{Balanced operations}: Given an equation, one can perform the same operation to both sides of the equation and maintain equality. The same is true for inequalities for the operation of addition, and for multiplication or division by a \emph{positive} number. \item Multiplying or dividing an inequality by a negative value will reverse the inequality symbol. \item The ratio of two integers can always be reduced to lowest terms, so that the numerator and denominator have no common factors. \end {enumerate} \begin{exercise}{4} Give specific examples for statements (A--D) given above. You may use either numbers or variables (or both) in your examples.. For (A) and (B), give one example for each of the following cases: (i) equality, (ii) strict inequality, (iii) nonstrict inequality. \end{exercise} %\section {Number Theory Rules} % %Given that a prime number $p$ evenly divides into a number $q$, it is true that the prime number $p$ must divide one of the factors of $q$. % %Given that the product of two numbers is equal to 0, then it is true that one of the numbers must be 0. \subsection {Exponentiation (VERY important)} Exponentiation is one of the key tools of abstract algebra. It is \emph{essential} that you know your exponent rules inside and out! \begin{enumerate}[(I)] \item Any nonzero number raised to the power of 0 is equal to 1. \footnote{ Technically $0^0$ is undefined, although often it is taken to be 1. Try it on your calculator!} \item A number raised to the sum of two exponents is the product of the same number raised to each individual exponent. \item A number raised to the power which is then raised to another power is equal to the same number raised to the product of the two powers. \item The reciprocal of a number raised to a positive power is the same number raised to the negative of that power. \item Taking the product of two numbers and raising to a given power is the same as taking the powers of the two numbers separately, then multiplying the results. \end{enumerate} \begin{exercise}{5} For each of the above items (I--V), give a general equation (using variables) that expresses the rule. For example one possible answer to (II) is: $x^{y+z} = x^y \cdot x^z$ . \end{exercise} \begin{exercise}{6} Write an equation that shows another way to express a number raised to a power that is the difference of two numbers. \end{exercise} \section{Test yourself} Test yourself with the following exercises. If you feel totally lost, I strongly recommend that you improve your basic algebra skills before continuing with this course. Trying to do higher math without a confident mastery of basic algebra is like trying to play baseball without knowing how to throw and catch. \begin{exercise}{7} Simplify the following expressions. Factor whenever possible \begin{multicols}{2} \begin{enumerate}[(a)] \item $ 2^4 4^2$ \item $ \dfrac{3^9}{9^3}$ \item $\left( \dfrac{5}{9} \right)^7 \left( \dfrac{9}{5} \right)^6$ \item $\dfrac{a^5}{a^7} \, \cdot \, \dfrac{a^3}{a}$ \item $x(y-1) - y(x-1)$ \end{enumerate} \end{multicols} \end{exercise} \begin{exercise}{8} Same instructions as the previous exercise. These examples are harder. (\emph{Hint}: It's usually best to make the base of an exponent as simple as possible. Notice for instance that $4^7 = (2^2)^7 = 2^{14}$.) \begin{multicols}{2} \begin{enumerate}[(a)] \item $6^{1/2\cdot}2^{1/6}\cdot3^{3/2}\cdot2^{1/3}$ \item $(9^3)(4^7)\left(\frac{1}{2}\right)^8\left(\frac{1}{12}\right)^6$ \item $4^5 \cdot 2^3 \cdot \left(\frac{1}{2}\right)^5 \cdot \left( \frac{1}{4} \right) ^3$ \item $2^3 \cdot 3^4 \cdot 4^5 \cdot 2^{-5} \cdot 3^{-4} \cdot 4^{-3}$ \item $\dfrac{x(x-3)+3(3-x)}{(x-3)^2}$ \end{enumerate} \end{multicols} \end{exercise} \begin{exercise}{9} Same instructions as the previous exercise. These examples are even harder. (\emph{Hint}: Each answer is a single term, there are no sums or differences of terms.) \begin{multicols}{2} \begin{enumerate}[(a)] \item $\dfrac{a^5 +a^3 - 2a^4}{(a-1)^2}$ \item $a^x b^{3x}(ab)^{-2x}(a^2 b)^{x/2}$ \item $(x+y^{-1})^{-2}(xy+1)^2$ \item $\dfrac{(3^x+9^x)(1-3^x)}{1-9^x})$ \item $\dfrac{3x^2 - x}{x-1} + \dfrac{2x}{1-x}$ \end{enumerate} \end{multicols} \end{exercise} \begin{exercise}{10} Find ALL real solutions to the following equations. \begin{multicols}{2} \begin{enumerate}[(a)] \item $x^2 = 5x$ \item $(x - \sqrt{7})(x+\sqrt{7}) = 2$ \item $2^{4+x} = 4(2^{2x})$ \item $3^{-x} = 3(3^{2x})$ \item $16^5 = x^4$ \item $\dfrac{1}{1 + 1/x} -1= -1/10$ \end{enumerate} \end{multicols} \end{exercise}
package com.zipato.model; import android.content.Context; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.TypeFactory; import java.io.FileInputStream; import java.io.FileOutputStream; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.concurrent.ConcurrentHashMap; public abstract class SimpleRepository<K, T> extends ConcurrentHashMap<K, T> { private final JavaType type; protected RepositoryFactory factory; public SimpleRepository() { Type superClass = getClass().<API key>(); if (superClass instanceof Class<?>) { // sanity check, should never happen throw new <API key>("Internal error: no type information"); } /* 22-Dec-2008, tatu: Not sure if this case is safe -- I suspect * it is possible to make it fail? * But let's deal with specific * case when we know an actual use case, and thereby suitable * workarounds for valid case(s) and/or error to throw * on invalid one(s). */ Type[] actualTypeArguments = ((ParameterizedType) superClass).<API key>(); Type type1 = actualTypeArguments[actualTypeArguments.length - 1]; // FIXME: ugly shit!! if (!(type1 instanceof Class)) { throw new <API key>("Internal error... Blah"); } type = TypeFactory.defaultInstance().constructArrayType((Class<?>) type1); } public void write() throws Exception { FileOutputStream fos = factory.getContext().openFileOutput(getFileName(), Context.MODE_PRIVATE); ObjectMapper mapper = factory.getRestTemplate().getMapper(); mapper.writeValue(fos, values()); fos.flush(); fos.close(); } public void restore() throws Exception { FileInputStream fis = factory.getContext().openFileInput(getFileName()); ObjectMapper mapper = factory.getRestTemplate().getMapper(); T[] ts = mapper.readValue(fis, type); fis.close(); clear(); addAll(ts); } protected String getFileName() { return getClass().getSimpleName(); } public abstract T add(T t); public void addAll(T[] ts) { for (T t : ts) { add(t); } } public void addAll(Iterable<T> ts) { for (T t : ts) { add(t); } } }
* {margin:0; padding:0; border:0; outline:0; font-weight:inherit; font-style:inherit; font-size:100%; font-family:inherit;} A { margin:0; padding:0; font-size:100%; font-weight:inherit; font-style:inherit; vertical-align:baseline; background:transparent; } BODY {line-height:1; color:black; background:white;} OL, UL {list-style:none;} TABLE {border-collapse:separate; border-spacing: 0;} CAPTION, TH, TD {text-align:left; font-weight:normal;} BLOCKQUOTE:before, BLOCKQUOTE:after, Q:before, Q:after {content:"";} BLOCKQUOTE, Q {quotes:"" "";} ARTICLE, ASIDE, DETAILS, FIGCAPTION, FIGURE, FOOTER, HEADER, HGROUP, NAV, SECTION {display:block;} AUDIO, CANVAS, VIDEO {display:inline-block; *display:inline; *zoom:1;} /* End Global Full Reset */ /* Prevent iOS text size adjust on device orientation change, without disabling user zoom HTML {-<API key>:100%; -ms-text-size-adjust:100%;} */ BODY {font-family:Arial,Tahoma,Helvetica,San Serif; font-size:62.5%; line-height:normal; text-align:center;} BODY DIV {text-align:left;} .text-large {font-size:75%;} .text-bigger {font-size:90%;} .text-biggest {font-size:100%;} /* Global Typography */ H1, H2, H3, H4, H5, H6 {line-height:1.3em; font-weight:bold;} H1 {color:#222; font-size:2.5em; padding:0.2em 0px;} H2 {color:#000; font-size:1.8em; padding:0.2em 0px;} H3 {color:#000; font-size:1.6em; padding:0.2em 0px;} H4 {color:#000; font-size:1.5em; padding:0.2em 0px;} H5 {color:#000; font-size:1.4em; padding:0.2em 0px;} H6 {color:#000; font-size:1.3em; padding:0.2em 0px;} P, DT, DD, BLOCKQUOTE {padding:0.5em 0px; color:#000; font-size:1.2em; line-height:1.5em;} BLOCKQUOTE {margin:0.4em 30px; font-size:1.4em; line-height:1.6em;} BLOCKQUOTE P, BLOCKQUOTE UL, BLOCKQUOTE OL {margin:0px; font-size:1em !important;} ::-moz-selection {background:#fe57a1; color:#fff; text-shadow:none;} ::selection {background:#fe57a1; color:#fff; text-shadow:none;} /* UL's need a background */ UL, OL {font-size:1.2em; line-height:1.5em;} UL {padding:0.5em 0px 0.5em 10px; list-style:none;} OL {padding:0.5em 0px 0.5em 30px; list-style:decimal;} LI UL, LI OL {padding-bottom:0em; font-size:1em;} LI {padding:0.2em 0px; color:#000;} UL > LI {padding-left:20px; background:url('../../../media/bullet-square-black.gif') 6px 0.8em no-repeat;} OL > LI {padding-left:0px; background:none;} /* Non image bullets LI {margin:0.2em 0px; color:#000;} LI UL, LI OL {margin:0.5em 0em 0.5em 0px; font-size:1em;} UL, OL {margin:0.5em 15px 0.5em 0px; padding-left:30px; font-size:1.2em; line-height:1.5em;} UL {list-style:square outside none;} OL {list-style:decimal outside none;} */ DL {padding:0px 5px 0.5em 14px;} DT, DD {padding:0.2em 0px;} DD {padding-left:20px;} DT {font-weight:bold;} DL P, DL UL, DL OL {font-size:1.0em !important;} HR {height:1px; line-height:1px; color:#666366; background:#666366; border:none;} /* Misc */ IMG {border:0px; vertical-align:bottom; font-size:1em; font-weight:bold; -<API key>:bicubic;} CODE {padding:0.5em; color:#000; font-size:1.2em; line-height:1.3em; font-family:Courier New, Serif;} ADDRESS {font-size:1.2em; font-style:italic;} STRONG {font-weight:bold;} SMALL {font-size:} EM {font-style:italic;} DFN {font-style:italic;} MARK {background:#df480d;} SUP, SUB {line-height:0; font-size:86%;} SUB {vertical-align:-0.2em;} SUP {vertical-align:0.6em;} PRE {white-space:pre; white-space:pre-wrap; word-wrap:break-word;} /* Inline Elements */ A {color:#df480d; text-decoration:underline;} A:visited {color:#e1774d;} A:hover, A:focus {color:#b0390a; background:#FFF none;} A:hover, A:active, A:focus {outline:none;} /* Table Elements */ TABLE {margin:0.5em 0px; border-collapse:collapse;} TD, TH {color:#000; font-size:1.2em; border:1px #555 solid; vertical-align:middle;} TH {font-weight:bold;} CAPTION {font-size:1.2em; font-style:italic;} TD, TH, CAPTION {padding:0.3em;} /* Form Elements (non ie6 version) */ LABEL {font-weight:bold; padding-top:2px;} LEGEND {*margin-left:-7px; white-space:normal;} FIELDSET {border:none;} INPUT, TEXTAREA, SELECT, LEGEND, LABEL, OPTION {color:#424242; font-family:Arial,Tahoma,Helvetica,San Serif;} INPUT, TEXTAREA, SELECT, LEGEND, LABEL {font-size:1.1em;} INPUT[type=text], TEXTAREA {padding:2px 0px 2px 3px;} INPUT[type=radio], INPUT[type=checkbox] {border:none; box-sizing:border-box; *width:13px; *height:13px;} INPUT[type="search"] {-webkit-appearance:textfield; -moz-box-sizing:content-box; -webkit-box-sizing:content-box; box-sizing:content-box;} INPUT[type="search"]::-<API key>, INPUT[type="search"]::-<API key> {-webkit-appearance:none;} BUTTON, INPUT[type=button], INPUT[type=reset], INPUT[type=submit] {curosr:pointer; -webkit-appearance:button; *overflow:visible;} BUTTON[disabled], INPUT[disabled] {cursor:default;} BUTTON::-moz-focus-inner, INPUT::-moz-focus-inner {border:0; padding:0;} /* Remove inner padding and border in FF3/4 */ SELECT, INPUT[type=text], TEXTAREA {border:1px #969696 solid;} SELECT:focus, SELECT:hover, INPUT[type=text]:focus, INPUT[type=text]:hover, TEXTAREA:focus, TEXTAREA:hover {border:1px #000 solid;} TEXTAREA {max-width:500px; max-height:500px; overflow:auto;} INPUT:valid, TEXTAREA:valid {} INPUT:invalid, TEXTAREA:invalid {background-color:#f0dddd;} /* Accessibility Elements */ #jumplinks, .visually-hidden {border:0 !important; clip:rect(0 0 0 0); height:1px !important; margin:-1px !important; overflow:hidden !important; padding:0 !important; position:absolute !important; width:1px !important;} ACRONYM, ABBR {border:none;} ACRONYM[title], ABBR[title] {cursor:help; border-bottom:1px dotted #AAA;} ABBR {speak:normal;} ACRONYM {speak:spell-out;} /* JavaScript Warnings <p class="js-warning">JS required to use this feature.</p> */ .js-warning {display:block;} SPAN.js-warning {display:inline;} .js .js-warning {display: none; visibility:hidden;} /* Hide for both screenreaders and browsers */ .hidden {display:none; visibility:hidden;} [hidden] {display:none;} /* Hide visually and from screenreaders, but maitain layout */ .invisible {visibility:hidden;} /* Flash, Iframe special etc. */ .flash OBJECT, .flash EMBED, .media OBJECT, .media EMBED, .iframe IFRAME {float:left;} SVG:not(:root) {overflow:hidden;} /* Ensure the element always fully contains its floated children */ .clearfix:before, .clearfix:after {content:""; display:table;} .clearfix:after {clear:both;} .clearfix {*zoom:1;} /* Structural Elements */ BODY{overflow:hidden;} #page{ width:100%; height:100%; position:relative; z-index:0; overflow:hidden; } /* Vignette */ #vignetteWrapper{ visibility:hidden; height:2500px;} #vignetteWrapper .vignette{position:fixed; z-index:1;} #vignetteWrapper .vignette > IMG{width: 100%;height: 100%;} .statements{ width:100%; height:100%; position:fixed; z-index:3; top:0; left:0; white-space:nowrap;} .statements DIV{float:left; width:0; height:100%; overflow:hidden; position:relative; z-index:4;} .statements .open-statement IMG, .statements .close-statement IMG{display:none; position:absolute; z-index:5;} .statements .bracket{float:left;} .navigation{width:50px; height:100%; position:fixed; z-index:6; top:0; right:0; background:transparent url(../../../media/nav-bg.png) repeat-y scroll 0 0;} .navigation .logo{display:block; width:18px; height:56px; margin:1.4em auto; background:transparent;} .navigation .logo IMG{width:100%; height:100%;} .shortcut{padding:0; font-size:1.6em;display:none;position:fixed;left:0;top:0;} .shortcut LI{margin:0; padding:0; position:relative; z-index:7; background:none;} .shortcut A{display:block; width:50px; height:50px; background:transparent;} .shortcut A IMG{display:none; width:100%; height:100%;} #loading{width:100%; height:100%; position:fixed; z-index:998; top:0; left:0; background:transparent url(../../../media/loading-bg.jpg) repeat scroll 50% 50%;} .loading-icon{width:60px; height:60px; margin:-30px 0 0 -30px; position:absolute; z-index:1000; left:50%; top:45%;} .loading-bar{width:200px; height:28px; margin:0 0 0 -100px; position:absolute; z-index:999; left:50%; top:55%; background:transparent url(../../../media/loading-bar.png) no-repeat scroll 0 0;} .loading-bar DIV{width:0; height:28px; background:transparent url(../../../media/loading-bar.png) no-repeat scroll 0 -30px;} #loading.complete{display:none;} #loading.complete .loading-bar DIV{width:100%;} .mail{display:none; width:60px; height:60px; margin:0 0 0 50%; position:fixed; z-index:6; left:-30px; top:60%; text-align:center;} .mail .icon{cursor:pointer;} .mail A{display:block; width:0; height:23px; padding:18px 0 19px 0; overflow:hidden; position:absolute; z-index:7; top:0; background:transparent;} .mail A IMG{display:block; padding:0 10px;} .mail .dealer{right:60px;} .mail .dealer IMG{position:absolute; z-index:8; right:0;} .mail .consumer{left:60px;} .mail .consumer IMG{position:absolute; z-index:8; left:0;} .fill-screen{z-index:1;} /* Unsupported */ #unsupported P{color:#fff; text-align:center; font-size:2em;} #unsupported .mail{display:block;} #pagelinks{display: block; height: 100px; width: 100px; position: fixed; top: 0; left: 100px; z-index: 9999;}
#include "stdafx.h" #include "GLCommonDecompiler.h" std::string <API key>(size_t elementCount) { switch (elementCount) { default: abort(); case 1: return "float"; case 2: return "vec2"; case 3: return "vec3"; case 4: return "vec4"; } } std::string getFunctionImpl(FUNCTION f) { switch (f) { default: abort(); case FUNCTION::FUNCTION_DP2: return "vec4(dot($0.xy, $1.xy))"; case FUNCTION::FUNCTION_DP2A: return ""; case FUNCTION::FUNCTION_DP3: return "vec4(dot($0.xyz, $1.xyz))"; case FUNCTION::FUNCTION_DP4: return "vec4(dot($0, $1))"; case FUNCTION::FUNCTION_DPH: return "vec4(dot(vec4($0.xyz, 1.0), $1))"; case FUNCTION::FUNCTION_SFL: return "vec4(0., 0., 0., 0.)"; case FUNCTION::FUNCTION_STR: return "vec4(1., 1., 1., 1.)"; case FUNCTION::FUNCTION_FRACT: return "fract($0)"; case FUNCTION::<API key>: return "texture($t, $0.xy)"; case FUNCTION::<API key>: return "textureProj($t, $0.xyz, $1.x)"; // Note: $1.x is bias case FUNCTION::<API key>: return "textureLod($t, $0.xy, $1)"; case FUNCTION::<API key>: return "texture($t, $0.xyz)"; case FUNCTION::<API key>: return "textureProj($t, $0.xyzw, $1.x)"; // Note: $1.x is bias case FUNCTION::<API key>: return "textureLod($t, $0.xyz, $1)"; case FUNCTION::FUNCTION_DFDX: return "dFdx($0)"; case FUNCTION::FUNCTION_DFDY: return "dFdy($0)"; } } std::string compareFunctionImpl(COMPARE f, const std::string &Op0, const std::string &Op1) { switch (f) { case COMPARE::FUNCTION_SEQ: return "equal(" + Op0 + ", " + Op1 + ")"; case COMPARE::FUNCTION_SGE: return "greaterThanEqual(" + Op0 + ", " + Op1 + ")"; case COMPARE::FUNCTION_SGT: return "greaterThan(" + Op0 + ", " + Op1 + ")"; case COMPARE::FUNCTION_SLE: return "lessThanEqual(" + Op0 + ", " + Op1 + ")"; case COMPARE::FUNCTION_SLT: return "lessThan(" + Op0 + ", " + Op1 + ")"; case COMPARE::FUNCTION_SNE: return "notEqual(" + Op0 + ", " + Op1 + ")"; } }
<?php if(isset($_POST['upload'])) { $cat_id = $_POST['categories_name']; $name= $_POST['name']; $small_img = $_FILES['image_small']['tmp_name']; $fa = fopen($small_img,"rb"); $data_small = fread($fa, filesize($small_img)); fclose($fa); $big_img = $_FILES['image_big']['tmp_name']; $fa2 = fopen($big_img,"rb"); $data_big = fread($fa2, filesize($big_img)); fclose($fa2); $price = $_POST['price']; $quantity = $_POST['quantity']; $weight = $_POST['weight']; $maker = $_POST['maker']; $color = $_POST['color']; $prod->insert_pro($cat_id,$name,$data_small,$data_big,$price,$quantity,$weight,$maker,$color); } ?> <style> .clear{ clear:both;} .trang{ width:620px; margin:auto; text-align:center; } .page-item{ border:thin #3CC solid; border-radius:3px; padding:3px; float:left; margin-left:3px; } .page-item:hover{ border:thin #3CC solid; border-radius:3px; padding:3px; float:left; margin-left:3px; background:pink; } .page-item-v{ border:thin #3CC solid; border-radius:3px; padding:3px; float:left; margin-left:3px; background:#FF0; } </style> <div id="content"> <div id="box"> <h3>Các loại danh mục sản phẩm</h3> <?php if($nums_page >0) { ?> <table width='100%'> <thead> <tr> <th width="40px">ID<img src="img/icons/arrow_down_mini.gif" width="16" height="16" align="absmiddle" /></th> <th>Tên sản phẩm</th> </tr> </thead> <tbody> <?php foreach($dataonepage as $key) { echo"<tr>"; echo"<td class='a-center'>"; echo $key[0]; echo "</td>"; echo "<td>"; echo "<a href='index_products.php?pid=".$key[0]."'>".$key[1]."</a>"; echo "</td>"; echo "</tr>"; } ?> </tbody> </table> <div id="pager"> <?php if($page >1) { echo "<a href='index_products.php?page=".($page-1)."'> <div class='page-item'>Trước</div> </a>"; } for($i=1;$i<=$nums_page;$i++) { if($i==$page) { echo "<div class='page-item-v' > <b> $i </b> </div>"; } else { echo "<a href='index_products.php?page=".$i."'> <div class='page-item'>".$i."</div> </a>"; } } } else { echo "<div id='content'> Hiện chưa có sản phẩm nào </div>"; } ?> </div> <br /> <div id="box"> <form id="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data"> <fieldset id="personal"> <legend>THÊM SẢN PHẨM MỚI</legend> <label for="name">Nhập tên sản phẩm : </label> <input name="name" id="name" type="text" tabindex="1" size="100" /> <br /> <label for="category">Chọn danh mục sản phẩm : </label> <select name='categories_name'> <?php foreach($datacat as $key) { echo "<option value="; echo $key[0]; echo ">".$key[1]."</option>"; } ?> </select> <br /> <label for="image_small">Tải ảnh cỡ nhỏ : </label> <input name="MAX_FILE_SIZE" value="102400" type="hidden"/> <input name="image_small" accept="image/jpeg" type="file" /> <br /> <label for="image_big">Tải ảnh cỡ lớn : </label> <input name="MAX_FILE_SIZE" value="204800" type="hidden" /> <input name="image_big" accept="image/jpeg" type="file" /> <br /> <label for="price">Nhập giá (VNĐ) : </label> <input name="price" id="price" type="text" tabindex="1" size="100" /> <br /> <label for="quantity">Nhập số lượng sản phẩm : </label> <input name="quantity" id="quantity" type="text" tabindex="1" size="100" /> <br /> <label for="weight">Nhập khối lượng sản phẩm : </label> <input name="weight" id="name" type="text" tabindex="1" size="100" /> <br /> <label for="maker">Nhập hãng sản xuất : </label> <input name="maker" id="maker" type="text" tabindex="1" size="100" /> <br /> <label for="color">Nhập màu sắc : </label> <input name="color" id="color" type="text" tabindex="1" size="100" /> <br /> </fieldset> <div align="center"> <input id="button1" type="submit" value="Gửi dữ liệu" name="upload" /> </div> </form> </div> </div>
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") local f = assert(io.popen('/usr/bin/git describe --tags', 'r')) VERSION = assert(f:read('*a')) f:close() -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end msg = backward_msg_format(msg) local receiver = get_receiver(msg) print(receiver) --vardump(msg) --vardump(msg) msg = <API key>(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) if redis:get("bot:markread") then if redis:get("bot:markread") == "on" then mark_read(receiver, ok_cb, false) end end end end end function ok_cb(extra, success, result) end function <API key>() started = true postpone (cron_plugins, false, 60*5.0) -- See plugins/isup.lua as an example for cron _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < os.time() - 5 then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then --send_large_msg(*group id*, msg.text) *login code will be sent to GroupID* return false end return true end function <API key>(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.<API key> table local function <API key>(plugin_name, receiver) local disabled_chats = _config.<API key> -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if <API key>(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not <API key>(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Sudo user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "OMAR", "supergroup", "me", "media", "help", "banhammer", "fwd_lock", "anti_spam", "block", "HI", "id", "kickbot", "link", "delmsg", "dev", "NewGroup", "lockreply", "plugins", "run", "run2", "Welcome", "getlink", "msg_checks", "version" }, sudo_users = {110626080,103649648,111020322,0,tonumber(our_id)},--Sudo users moderation = {data = 'data/moderation.json'}, about_text = [[ Made BY @Omar_Real ]], } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) --vardump (chat) end function <API key> (schat, what) --vardump (schat) end function <API key> () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all'))) print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
package com.ctreber.acearth.shader; import java.awt.Color; /** * <p>Shader for the orthographic projection.</p> * * <p>&copy; 2002 Christian Treber, ct@ctreber.com (Nov 11, 2002)</p> * @author Christian Treber, ct@ctreber.com * */ public class ShaderOrtho extends Shader { private static double[] fXValues; public Color[] getShadedColors(int pRowNo, int[] pRowTypes) { if(pRowNo == 0) { fXValues = computeXValues(pRowTypes.length); } final double y = fProjection.inverseProjectY(fProjection.inverseFinalizeY(pRowNo)); final double tmp = 1 - (y * y); final double lYBySunVectorY = y * fLightVector.getY(); final Color[] lColors = new Color[pRowTypes.length]; for(int lColNo = 0; lColNo < pRowTypes.length; lColNo++) { double x = fXValues[lColNo]; double z = Math.sqrt(tmp - (x * x)); double lSunValue = (x * fLightVector.getX()) + lYBySunVectorY + (z * fLightVector.getZ()); lColors[lColNo] = <API key>(pRowTypes[lColNo], lSunValue); } return lColors; } /** * * @return X value for each column in image. */ private double[] computeXValues(int pWidth) { final double[] lTable = new double[pWidth]; for(int lColNo = 0; lColNo < pWidth; lColNo++) { lTable[lColNo] = fProjection.inverseProjectX(fProjection.inverseFinalizeX(lColNo)); } return lTable; } }
<?php // If uninstall not called from WordPress, then exit if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) { exit; } // @TODO: Define uninstall functionality here
var <API key> = 20; var bounds_ContactMap = new google.maps.LatLngBounds(); var marker_map = new Array(); var marker_pano_open = new Array(); var marker_pano; var markers_pano = {}; var index_pano = 0; var <API key> = false; var delete_old_pano = true; /* Charge les photos Paroramio contenu dans la carte visible */ function <API key>() { var url = 'http: var bounds = carteContactMap.getBounds(); url += '&minx=' + bounds.getSouthWest().lng().toFixed(6) + '&miny=' + bounds.getSouthWest().lat().toFixed(6); url += '&maxx=' + bounds.getNorthEast().lng().toFixed(6) + '&maxy=' + bounds.getNorthEast().lat().toFixed(6); url += '&ts=' + new Date().getTime(); // prevent caching // use JSONP to retrieve photo data and trigger a callback to addPhotos() var script = document.createElement("script"); script.setAttribute("src", url); script.setAttribute("type", "text/javascript"); document.body.appendChild(script); } // Ajoute les marqueurs Panoramino function addPhotosPanoramino(data) { var new_markers_pano = {}; function <API key>(marker,photo){ var infowindow = new google.maps.InfoWindow({ content: '<a href="'+photo.photo_url+'" target="_blank"><img src="http://mw2.google.com/mw-panoramio/photos/small/'+photo.photo_id+'.jpg" ></a><div class="<API key>">'+photo.photo_title+'</div>' }); google.maps.event.addListener(marker, 'click', function(e) { marker_pano_open[photo.photo_id] = marker; infowindow.setZIndex(++infowindowLevel); infowindow.open(carteContactMap,marker); }); google.maps.event.addListener(infowindow, 'closeclick', function(e) { delete marker_pano_open[photo.photo_id]; }); } if (data.photos && data.photos.length) { for (var i = 0; i < data.photos.length; i++) { var photo = data.photos[i]; // Pour un gain de vitesse et de confort visuel conserve les marqueurs existant if (photo.photo_id in markers_pano) { new_markers_pano[photo.photo_id] = markers_pano[photo.photo_id]; } else { var maLatLng = new google.maps.LatLng(photo.latitude, photo.longitude); marker_pano = new google.maps.Marker({ map: carteContactMap, position: maLatLng, title: photo.photo_title, icon: photo.photo_file_url }); <API key>(marker_pano,photo); new_markers_pano[photo.photo_id] = marker_pano; }; } } // supprime les anciens marqueurs if (delete_old_pano) { for (var photo_id in markers_pano) { if ((!(photo_id in new_markers_pano))&&(!(photo_id in marker_pano_open))) { markers_pano[photo_id].setMap(null); delete markers_pano[photo_id]; } } } //garde en memoire les marqueurs dont l'infowindow est ouverte for (var photo_id in marker_pano_open) { new_markers_pano[photo_id] = marker_pano_open[photo_id]; } markers_pano = new_markers_pano; } function delete_markers_pano(){ for (var photo_id in markers_pano) { markers_pano[photo_id].setMap(null); delete markers_pano[photo_id]; } } function show_markers_pano(){ <API key>(); } function activate_pano(){ <API key> = true; <API key>(); } function desactivate_pano(){ <API key> = false; delete_markers_pano(); } function inverse_pano(){ if (!<API key>) { activate_pano(); }else{ desactivate_pano(); } } var geoXml; /* function loadDataWikipedia() { geoXml = new geoXML3.parser({ zoom: true, processStyles: true, markerOptions: {map: carteContactMap, shadow: null}, infoWindowOptions: {pixelOffset: new google.maps.Size(0, 12)}, singleInfoWindow: true, createMarker: addMarker, afterParse: parsed, failedParse: failed }); alert('tutu'); var bounds = carteContactMap.getBounds(); var url = 'data/wikipedia_bounds.kml.php?maxRows=10&west=' + mapBounds.getSouthWest().lng().toFixed(6) + '&north=' + mapBounds.getNorthEast().lat().toFixed(6) + '&east=' + mapBounds.getNorthEast().lng().toFixed(6) + '&south=' + mapBounds.getSouthWest().lat().toFixed(6); // Load the KML - new markers will be added when it returns alert(geoXml.parse(url)); } function addMarker(placemark) { var coordinates = new google.maps.LatLng(placemark.point.lat, placemark.point.lng); for (var m = markers.length - 1; m >= 0; m--) { if (markers[m].get_position().equals(coordinates)) { return; } } var marker = geoXml.createMarker(placemark); markers.push(marker); }; */ function CalculRoute(num) { if (document.getElementById("select_from"+num).value != "") { fromAddress = document.getElementById("select_from"+num).value; } else { fromAddress = document.getElementById("text_from"+num).value; }; if (document.getElementById("select_to"+num).value != "") { toAddress = document.getElementById("select_to"+num).value; } else { toAddress = document.getElementById("text_to"+num).value; }; var request = { origin:fromAddress, destination:toAddress, travelMode: google.maps.<API key>.DRIVING }; directionsService.route(request, function(response, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response); } }); } /* Affiche le menu more options */ var chicago = new google.maps.LatLng(41.850033, -87.6500523); // Define a property to hold the More state MoreControl.prototype.home_ = null; // Define setters and getters for this property MoreControl.prototype.getMore = function() { control.setMorePano.style.display = 'block'; alert('fc_getmore'); //return this.home_; } MoreControl.prototype.setMore = function(home) { alert('fc_setMore'); //this.home_ = home; } function MoreControl(map, div) { var visible = false; // Get the control DIV. We'll attach our control UI to this DIV. var controlDiv = div; // We set up a variable for the 'this' keyword since we're adding event // listeners later and 'this' will be out of scope. var control = this; // Set CSS styles for the DIV containing the control. Setting padding to // 5 px will offset the control from the edge of the map controlDiv.style.padding = '5px'; // Set CSS for the control border var MoreUI = document.createElement('DIV'); MoreUI.style.backgroundColor = 'white'; MoreUI.style.borderStyle = 'solid'; MoreUI.style.borderWidth = '2px'; MoreUI.style.cursor = 'pointer'; MoreUI.style.textAlign = 'center'; MoreUI.style.width = '120px'; MoreUI.title = 'Click to set 1'; controlDiv.appendChild(MoreUI); // Set CSS for the control interior var MoreText = document.createElement('DIV'); MoreText.style.fontFamily = 'Arial,sans-serif'; MoreText.style.fontSize = '12px'; MoreText.style.paddingLeft = '4px'; MoreText.style.paddingRight = '4px'; MoreText.style.color = 'black'; MoreText.innerHTML = '<b>More</b><img style="position: absolute; right: 9px; top: 9px; display: block; " src="http://maps.gstatic.com/intl/fr_ALL/mapfiles/down-arrow.gif">'; MoreUI.appendChild(MoreText); // Set CSS for the setMore control border var MoreDisplayUI = document.createElement('DIV'); MoreDisplayUI.style.backgroundColor = 'white'; MoreDisplayUI.style.borderStyle = 'solid'; MoreDisplayUI.style.borderWidth = '1px'; MoreDisplayUI.style.cursor = 'pointer'; MoreDisplayUI.style.textAlign = 'center'; MoreDisplayUI.style.fontFamily = 'Arial,sans-serif'; MoreDisplayUI.style.fontSize = '12px'; MoreDisplayUI.style.paddingLeft = '4px'; MoreDisplayUI.style.paddingRight = '4px'; MoreDisplayUI.style.color = 'black'; MoreDisplayUI.style.display = 'none'; MoreDisplayUI.title = 'Click to set 2'; controlDiv.appendChild(MoreDisplayUI); // Set CSS for the control interior var Pano = document.createElement('DIV'); var Vchecked = ""; if (<API key>) Vchecked = "checked"; Pano.innerHTML = '<input name="mark_contactmap" type="checkbox" '+Vchecked+' onclick="inverse_pano()" /> Panoramino <br />'; MoreDisplayUI.appendChild(Pano); /* var setMoreText = document.createElement('DIV'); setMoreText.innerHTML = '<input name="mark_contactmap" type="checkbox" onclick="<API key>(this.checked, layers_contactmap[0].obj)" /> Photos <br />'; MoreDisplayUI.appendChild(setMoreText); */ // Setup the click event listener for More: google.maps.event.addDomListener(MoreUI, 'click', function() { if (visible) { MoreDisplayUI.style.display = 'none'; visible = false; }else{ MoreDisplayUI.style.display = 'block'; visible = true; } }); }
<?php // Check to ensure this file is included in Joomla! defined('_JEXEC') or die(); JTable::addIncludePath(<API key>.DS.'tables'); /** * Translator Extension Controller * * @package yos_translator * @subpackage Components */ class <API key> extends <API key> { /** * constructor (registers additional tasks to methods) * @return void */ var $_notran = array(); function __construct() { parent::__construct(); } function edit(){ $view=$this->getView('<API key>','html'); if ($model=& $this->getModel('<API key>')) { $view->setModel($model); $view->setLayout('form'); } $view->display(); } function save(){ global $mainframe; $id = JRequest::getInt('id'); $src= JRequest::getString('src'); $dst= JRequest::getInt('dst'); $published = JRequest::getString('published'); $published = $published == 'true' ? 1 : 0; $lang_id = $dst; $lang = &JTable::getInstance('languages'); $lang->load($dst); $db = &JFactory::getDBO(); $query = "SELECT code_translator FROM #__yos_translator WHERE code_language = '$lang->code'"; $db->setQuery($query); $dst = $db->loadResult(); if (!$dst) { echo 'Error!'; die(); } $content =& JTable::getInstance('content','Table'); $content->load((int)$id); //build a page to translate $pageContent = ''; $titleHashBegin = md5('<API key>'); $titleHashEnd = md5('<API key>'); $pageContent .= '' . $titleHashBegin . '<div>' . $content->title . '</div>' . $titleHashEnd . ''; $pageContent .= "<br />"; $introtextHashBegin = md5('<API key>'); $introtextHashEnd = md5('<API key>'); $pageContent .= '' . $introtextHashBegin . '<div>' . $content->introtext . '</div>' . $introtextHashEnd . ''; $pageContent .= "<br />"; $fulltextHashBegin = md5('<API key>'); $fulltextHashEnd = md5('<API key>'); $pageContent .= '' . $fulltextHashBegin . '<div>' . $content->fulltext . '</div>' . $fulltextHashEnd . ''; $pageContent .= "<br />"; $metakeyHashBegin = md5('<API key>'); $metakeyHashEnd = md5('<API key>'); $pageContent .= '' . $metakeyHashBegin . '<div>' . $content->metakey . '</div>' . $metakeyHashEnd . ''; $pageContent .= "<br />"; $metadescHashBegin = md5('<API key>'); $metadescHashEnd = md5('<API key>'); $pageContent .= '' . $metadescHashBegin . '<div>' . $content->metadesc . '</div>' . $metadescHashEnd . ''; $pageContent .= "<br />"; //No translate $pageContent = $this->notranslate($pageContent); $pageContent = $this->personconfig($pageContent); //require helper require_once(<API key>.DS.'helpers'.DS.'translator.php'); $translator = new Yos_translator(); $languagePair = $src.'|'.$dst; $language_from = JRequest::getString('from_lang', ''); if ($language_from != '') { //get code of language to //$code_to = $model->_getLanguageCode($translate_to); $languagePair = $language_from.'|'.$dst; } $tsl_pageContent = $translator->translate($languagePair, $pageContent); //Prepare save content if (count($this->_notran)) { foreach ($this->_notran as $notran) { $tsl_pageContent = str_replace($notran['hash'], $notran['value'], $tsl_pageContent); } } //remove old translated records $query = "DELETE FROM #__jf_content WHERE reference_id = $id AND language_id = $lang_id AND reference_table= 'content'"; $db->setQuery($query); $db->query(); //get table JTable::addIncludePath(<API key>.DS.'tables'); $tbl_jf_content =& JTable::getInstance('jf_content', 'Table'); //get title: if (preg_match('/' . $titleHashBegin . '\s*<div>(.*?)<\/div>\s*' . $titleHashEnd . '/is', $tsl_pageContent, $match)) { $title = str_replace('&quot;','"',trim($match[1])); $tbl_jf_content->store_jf($lang_id, $id, 'content', 'title', $title, md5($content->title), $content->title, $published); } //get introtext: if (preg_match('/' . $introtextHashBegin . '\s*<div>(.*?)<\/div>\s*' . $introtextHashEnd . '/is', $tsl_pageContent, $match)) { $tbl_jf_content->store_jf($lang_id, $id, 'content', 'introtext', trim($match[1]), md5($content->introtext), $content->introtext, $published); } //get fulltext: if (preg_match('/' . $fulltextHashBegin . '\s*<div>(.*?)<\/div>\s*' . $fulltextHashEnd . '/is', $tsl_pageContent, $match)) { $tbl_jf_content->store_jf($lang_id, $id, 'content', 'fulltext', trim($match[1]), md5($content->fulltext), $content->fulltext, $published); } //get metakey: if (preg_match('/' . $metakeyHashBegin . '\s*<div>(.*?)<\/div>\s*' . $metakeyHashEnd . '/is', $tsl_pageContent, $match)) { $tbl_jf_content->store_jf($lang_id, $id, 'content', 'metakey', trim($match[1]), md5($content->metakey), $content->metakey, $published); } //get metadesk: if (preg_match('/' . $metadescHashBegin . '\s*<div>(.*?)<\/div>\s*' . $metadescHashEnd . '/is', $tsl_pageContent, $match)) { $tbl_jf_content->store_jf($lang_id, $id, 'content', 'metadesc', trim($match[1]), md5($content->metadesc), $content->metadesc, $published); } //copy alias, images, publish_up, publish_down, atribs fields $tbl_jf_content->store_jf($lang_id, $id, 'content', 'alias', $content->alias, md5($content->alias), $content->alias, $published); $tbl_jf_content->store_jf($lang_id, $id, 'content', 'images', $content->images, md5($content->images), $content->images, $published); $tbl_jf_content->store_jf($lang_id, $id, 'content', 'publish_up', $content->publish_up, md5($content->publish_up), $content->publish_up, $published); $tbl_jf_content->store_jf($lang_id, $id, 'content', 'publish_down', $content->publish_down, md5($content->publish_down), $content->publish_down, $published); $tbl_jf_content->store_jf($lang_id, $id, 'content', 'attribs', $content->attribs, md5($content->attribs), $content->attribs, $published); die(); } /** * Dump to notranslate data * * @param content data $data * @return content data */ function notranslate($data){ $regex = '/\{notranslate\}(.*?)\{\/notranslate\}/m'; preg_match_all($regex, $data, $matches); $f_number = count($matches[0]); if (!$f_number) { return $data; } for ($i =0 ; $i<$f_number; $i++){ $data = str_replace($matches[0][$i], md5($matches[0][$i]),$data); $this->_notran[] = array('hash'=> md5($matches[0][$i]), 'value'=> $matches[1][$i]); } return $data; } /** * Replace personconfig to notranslate and dump it * * @param content data $data * @return content data */ function personconfig( $data ){ $config =& JComponentHelper::getParams('com_yos_translator'); $param_notranslate= $config->get('notranslate'); $param_notranslate= preg_replace('/\s/','',$param_notranslate); if ($param_notranslate) { $arr_tag = explode(';',$param_notranslate); foreach ($arr_tag as $tag) { if ($tag) { $arr_sp = explode(',', $tag); $tagfirst = $arr_sp[0]; $taglast = $arr_sp[1]; if (!($tagfirst && $taglast)) { continue; } preg_match_all('/'.str_replace('/','\/',preg_quote($tagfirst)).'(.*?)'.str_replace('/','\/',preg_quote($taglast)).'/', $data, $matches); $f_number = count($matches[0]); if (!$f_number) { continue; } for ($i =0 ; $i<$f_number; $i++){ $data = str_replace($matches[0][$i], md5($matches[0][$i]),$data); $this->_notran[] = array('hash'=> md5($matches[0][$i]), 'value'=> $matches[0][$i]); } } } } return $data; } function cancel(){ global $mainframe, $option; $msg = "Operation aborted!"; $mainframe->redirect( "index.php?option=$option&view=contents", $msg ); } }
import os def enumFeeds(): for fn in os.listdir('/etc/opkg'): if fn.endswith('-feed.conf'): try: for feed in open(os.path.join('/etc/opkg', fn)): yield feed.split()[1] except IndexError: pass except IOError: pass def enumPlugins(filter_start=''): for feed in enumFeeds(): package = None try: for line in open('/var/lib/opkg/lists/%s' % feed, 'r'): if line.startswith('Package:'): package = line.split(":",1)[1].strip() version = '' description = '' if package.startswith(filter_start) and not package.endswith('-dev') and not package.endswith('-staticdev') and not package.endswith('-dbg') and not package.endswith('-doc') and not package.endswith('-src') and not package.endswith('-po'): continue package = None if package is None: continue if line.startswith('Version:'): version = line.split(":",1)[1].strip() elif line.startswith('Description:'): description = line.split(":",1)[1].strip() elif description and line.startswith(' '): description += line[:-1] elif len(line) <= 1: d = description.split(' ',3) if len(d) > 3: # Get rid of annoying "version" and package repeating strings if d[1] == 'version': description = d[3] if description.startswith('gitAUTOINC'): description = description.split(' ',1)[1] yield package, version, description.strip() package = None except IOError: pass if __name__ == '__main__': for p in enumPlugins('enigma'): print p
#include <arch/io.h> #include <console/console.h> #include <cpu/x86/smm.h> #include "southbridge/intel/ibexpeak/nvs.h" #include "southbridge/intel/ibexpeak/pch.h" #include "southbridge/intel/ibexpeak/me.h" #include <northbridge/intel/nehalem/nehalem.h> #include <cpu/intel/model_2065x/model_2065x.h> #include <ec/acpi/ec.h> #include <pc80/mc146818rtc.h> #include <ec/lenovo/h8/h8.h> #include <delay.h> #include "dock.h" #include "smi.h" #define GPE_EC_SCI 1 #define GPE_EC_WAKE 13 /* The southbridge SMI handler checks whether gnvs has a * valid pointer before calling the trap handler */ extern global_nvs_t *gnvs; static void mainboard_smm_init(void) { printk(BIOS_DEBUG, "initializing SMI\n"); /* Enable 0x1600/0x1600 register pair */ ec_set_bit(0x00, 0x05); } int <API key>(int smif) { static int smm_initialized; if (!smm_initialized) { mainboard_smm_init(); smm_initialized = 1; } switch (smif) { case SMI_DOCK_CONNECT: ec_clr_bit(0x03, 2); udelay(250000); dock_connect(); ec_set_bit(0x03, 2); /* set dock LED to indicate status */ ec_write(0x0c, 0x09); ec_write(0x0c, 0x88); break; case SMI_DOCK_DISCONNECT: ec_clr_bit(0x03, 2); dock_disconnect(); break; default: return 0; } /* On success, the IO Trap Handler returns 1 * On failure, the IO Trap Handler returns a value != 1 */ return 1; } static void <API key>(void) { u8 value; if ((value = pci_read_config8(PCI_DEV(0, 2, 1), 0xf4)) < 0xf0) pci_write_config8(PCI_DEV(0, 2, 1), 0xf4, (value + 0x10) | 0xf); } static void <API key>(void) { u8 value; if ((value = pci_read_config8(PCI_DEV(0, 2, 1), 0xf4)) > 0x10) pci_write_config8(PCI_DEV(0, 2, 1), 0xf4, (value - 0x10) & 0xf0); } static void <API key>(void) { u8 status = inb(EC_SC); u8 event; if (!(status & EC_SCI_EVT)) return; event = ec_query(); printk(BIOS_DEBUG, "EC event %02x\n", event); switch (event) { case 0x14: /* brightness up */ <API key>(); break; case 0x15: /* brightness down */ <API key>(); break; case 0x18: /* Fn-F9 key */ case 0x27: /* Power loss */ case 0x50: /* Undock Key */ <API key>(SMI_DOCK_DISCONNECT); break; case 0x37: case 0x58: /* Dock Event */ <API key>(SMI_DOCK_CONNECT); break; default: break; } } void mainboard_smi_gpi(u32 gpi_sts) { if (gpi_sts & (1 << GPE_EC_SCI)) <API key>(); } static int mainboard_finalized = 0; int mainboard_smi_apmc(u8 data) { switch (data) { case APM_CNT_FINALIZE: printk(BIOS_DEBUG, "APMC: FINALIZE\n"); if (mainboard_finalized) { printk(BIOS_DEBUG, "APMC#: Already finalized\n"); return 0; } <API key>(); <API key>(); <API key>(); <API key>(); mainboard_finalized = 1; break; case APM_CNT_ACPI_ENABLE: /* use 0x1600/0x1604 to prevent races with userspace */ ec_set_ports(0x1604, 0x1600); /* route H8SCI to SCI */ gpi_route_interrupt(GPE_EC_SCI, GPI_IS_SCI); /* discard all events, and enable attention */ ec_write(0x80, 0x01); break; case <API key>: /* we have to use port 0x62/0x66, as 0x1600/0x1604 doesn't provide a EC query function */ ec_set_ports(0x66, 0x62); /* route H8SCI# to SMI */ gpi_route_interrupt(GPE_EC_SCI, GPI_IS_SMI); /* discard all events, and enable attention */ ec_write(0x80, 0x01); break; default: break; } return 0; } void mainboard_smi_sleep(u8 slp_typ) { if (slp_typ == 3) { u8 ec_wake = ec_read(0x32); /* If EC wake events are enabled, enable wake on EC WAKE GPE. */ if (ec_wake & 0x14) { /* Redirect EC WAKE GPE to SCI. */ gpi_route_interrupt(GPE_EC_WAKE, GPI_IS_SCI); } } }
Imports MySql.Data.MySqlClient Module ModMsysql Public Sqlcn1 As New MySqlConnection Public SqlCmd1 As New MySqlCommand Public vSqlTimeout As Integer = 60 Public strCnn As String Public Sub Abre_conexion() Dim Configreader As System.Configuration.AppSettingsReader Configreader = New System.Configuration.AppSettingsReader Dim Vuser As String Dim Vpass As String Dim Vdatabase As String Dim Vserver As String Vserver = CStr(Configreader.GetValue("server", GetType(String))) Vdatabase = CStr(Configreader.GetValue("database", GetType(String))) Vuser = CStr(Configreader.GetValue("user", GetType(String))) Vpass = CStr(Configreader.GetValue("pass", GetType(String))) vSqlTimeout = CInt(Configreader.GetValue("TimeOut", GetType(Integer))) strCnn = "Data Source=" & Vserver & ";Database=" & Vdatabase & ";User Id=" & Vuser & ";Password=" & Vpass & ";" Sqlcn1.ConnectionString = strCnn End Sub Public Function RutDigito(ByVal Rut As Long) As String Dim Digito As Integer Dim Contador As Integer Dim Multiplo As Integer Dim Acumulador As Integer Contador = 2 Acumulador = 0 While Rut <> 0 Multiplo = (Rut Mod 10) * Contador Acumulador = Acumulador + Multiplo Rut = Rut \ 10 Contador = Contador + 1 If Contador = 8 Then Contador = 2 End If End While Digito = 11 - (Acumulador Mod 11) RutDigito = CStr(Digito) If Digito = 10 Then RutDigito = "K" If Digito = 11 Then RutDigito = "0" End Function End Module
#include"stdhdr.h" #include"zcchdr.h" //union align { //double d; //int (*pf) (); struct block { char *avail; char *limit; struct block *next; }; union header { struct block b; union align a; }; static struct block first[] = {{ NULL, }, { NULL, }, { NULL, }, {NULL, }}, *arena[] = {&first[0], &first[1], &first[2], &first[3]}; static struct block *free_blocks; void *zcc_alloc(int n, int a) { struct block *ap; int m; assert(a <= PERM); assert(n > 0); ap = arena[a]; _align(&n, sizeof(union align)); while (n > ap->limit - ap->avail) { if ((ap->next = free_blocks) != NULL) { free_blocks = free_blocks->next; ap = ap->next; } else { m = sizeof(union header) + n + 10*1024; _align(&m, sizeof(union align)); ap->next = malloc(m); ap = ap->next; if (ap == NULL) error(-1, -1, "malloc failed\n"); ap->limit = (char *)ap + m; } ap->avail = (char *)((union header *)ap + 1); ap->next = NULL; arena[a] = ap; } ap->avail += n; return ap->avail - n; } void zcc_free(int a) { assert(a < AELEMS(arena)); arena[a]->next = free_blocks; free_blocks = first[a].next; first[a].next = NULL; arena[a] = &first[a]; return; }
# Makefile.in generated by automake 1.11 from Makefile.am. # testing/setops/Makefile. Generated from Makefile.in by configure. # 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, # Inc. # This Makefile.in is free software; the Free Software Foundation # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # PARTICULAR PURPOSE. pkgdatadir = $(datadir)/mcl pkgincludedir = $(includedir)/mcl pkglibdir = $(libdir)/mcl pkglibexecdir = $(libexecdir)/mcl am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(<API key>) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = <API key> host_triplet = <API key> DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in \ $(top_srcdir)/include/include.am subdir = testing/setops ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(<API key>) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = <API key> = SOURCES = DIST_SOURCES = DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = ${SHELL} /panfs/panspermia/120274/git/proxigenomics/clustering/mcl-12-135/autofoo/missing --run aclocal-1.11 AMTAR = ${SHELL} /panfs/panspermia/120274/git/proxigenomics/clustering/mcl-12-135/autofoo/missing --run tar AUTOCONF = ${SHELL} /panfs/panspermia/120274/git/proxigenomics/clustering/mcl-12-135/autofoo/missing --run autoconf AUTOHEADER = ${SHELL} /panfs/panspermia/120274/git/proxigenomics/clustering/mcl-12-135/autofoo/missing --run autoheader AUTOMAKE = ${SHELL} /panfs/panspermia/120274/git/proxigenomics/clustering/mcl-12-135/autofoo/missing --run automake-1.11 AWK = gawk CC = gcc CCDEPMODE = depmode=gcc3 CFLAGS = -g -O2 -pthread CPP = gcc -E CPPFLAGS = CYGPATH_W = echo DEFS = -DHAVE_CONFIG_H DEPDIR = .deps ECHO_C = ECHO_N = -n ECHO_T = EGREP = /bin/grep -E EXEEXT = GREP = /bin/grep INSTALL = /usr/bin/install -c INSTALL_DATA = ${INSTALL} -m 644 INSTALL_PROGRAM = ${INSTALL} INSTALL_SCRIPT = ${INSTALL} <API key> = $(install_sh) -c -s LDFLAGS = LIBOBJS = LIBS = -lm LN_S = ln -s LTLIBOBJS = MAINT = MAKEINFO = ${SHELL} /panfs/panspermia/120274/git/proxigenomics/clustering/mcl-12-135/autofoo/missing --run makeinfo MKDIR_P = /bin/mkdir -p OBJEXT = o PACKAGE = mcl PACKAGE_BUGREPORT = mcl-devel@lists.micans.org PACKAGE_NAME = mcl PACKAGE_STRING = mcl 12-135 PACKAGE_TARNAME = mcl PACKAGE_URL = PACKAGE_VERSION = 12-135 PATH_SEPARATOR = : PTHREAD_CC = gcc PTHREAD_CFLAGS = -pthread PTHREAD_LIBS = RANLIB = ranlib SET_MAKE = SHELL = /bin/sh STRIP = VERSION = 12-135 abs_builddir = /panfs/panspermia/120274/git/proxigenomics/clustering/mcl-12-135/testing/setops abs_srcdir = /panfs/panspermia/120274/git/proxigenomics/clustering/mcl-12-135/testing/setops abs_top_builddir = /panfs/panspermia/120274/git/proxigenomics/clustering/mcl-12-135 abs_top_srcdir = /panfs/panspermia/120274/git/proxigenomics/clustering/mcl-12-135 ac_ct_CC = gcc acx_pthread_config = am__include = include am__leading_dot = . am__quote = am__tar = ${AMTAR} chof - "$$tardir" am__untar = ${AMTAR} xf - bindir = ${exec_prefix}/bin build = <API key> build_alias = build_cpu = x86_64 build_os = linux-gnu build_vendor = unknown builddir = . datadir = ${datarootdir} datarootdir = ${prefix}/share docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} dvidir = ${docdir} exec_prefix = ${prefix} host = <API key> host_alias = host_cpu = x86_64 host_os = linux-gnu host_vendor = unknown htmldir = ${docdir} includedir = ${prefix}/include infodir = ${datarootdir}/info install_sh = ${SHELL} /panfs/panspermia/120274/git/proxigenomics/clustering/mcl-12-135/autofoo/install-sh libdir = ${exec_prefix}/lib libexecdir = ${exec_prefix}/libexec localedir = ${datarootdir}/locale localstatedir = ${prefix}/var mandir = ${datarootdir}/man mkdir_p = /bin/mkdir -p oldincludedir = /usr/include pdfdir = ${docdir} prefix = /panfs/panspermia/120274 <API key> = s,x,x, psdir = ${docdir} sbindir = ${exec_prefix}/sbin sharedstatedir = ${prefix}/com srcdir = . sysconfdir = ${prefix}/etc target_alias = top_build_prefix = ../../ top_builddir = ../.. top_srcdir = ../.. INCLUDES = -I$(top_srcdir)/src -I$(top_srcdir) LDADD = ../mcl/libmcl.a ../clew/libclew.a ../gryphon/libgryphon.a ../impala/libimpala.a ../../util/libutil.a AM_LDFLAGS = -lm this = set-test.sh EXTRA_DIST = $(this) all: all-am .SUFFIXES: $(srcdir)/Makefile.in: # $(srcdir)/Makefile.am $(top_srcdir)/include/include.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu testing/setops/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu testing/setops/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(<API key>) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: # $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): # $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): tags: TAGS TAGS: ctags: CTAGS CTAGS: distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(<API key>)" \ install_sh_PROGRAM="$(<API key>)" INSTALL_STRIP_FLAG=-s \ `test -z '$(STRIP)' || \ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(<API key>)" || rm -f $(<API key>) <API key>: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am <API key> mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: all all-am check check-am clean clean-generic distclean \ distclean-generic distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ maintainer-clean <API key> mostlyclean \ mostlyclean-generic pdf pdf-am ps ps-am uninstall uninstall-am # AM_LDFLAGS = -lm -lunwind -ltcmalloc # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT:
# <API key> The program uses the Marvel API to search for comics by series, and returns a list of all the comics in the series. These comics release dates can then be added to your Google calender. A file will need to be created called keys.config next to the executable with the following format which needs your marvel public and private key. It will also need your google calender adress in the format "blahblah@group.calendar.google.com" <appSettings> <add key="publicKey" value="" /> <add key="privateKey" value="" /> <add key="calenderAddress" value="" /> </appSettings> TODO: Other calender integration (.ics .vcs files etc.) Better searching Better GUI
using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Windows.Data; namespace ClientsManager.Converters { public class DateConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value != null) return ((DateTime)value).Ticks == 0 ? "(not set)" : ((DateTime)value).ToString("dd.MM.yyyy"); else return "(not set)"; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new <API key>(); } } }
#define pr_fmt(fmt) "%s: " fmt, __func__ #include "mdss_fb.h" #include "mdss_mdp.h" #include <linux/uaccess.h> #include <linux/spinlock.h> #include <linux/delay.h> #include <mach/msm_bus.h> #include <mach/msm_bus_board.h> #include "mdss_mdp_kcal_ctrl.h" struct mdp_csc_cfg mdp_csc_convert[MDSS_MDP_MAX_CSC] = { [<API key>] = { 0, { 0x0200, 0x0000, 0x0000, 0x0000, 0x0200, 0x0000, 0x0000, 0x0000, 0x0200, }, { 0x0, 0x0, 0x0,}, { 0x0, 0x0, 0x0,}, { 0x0, 0xff, 0x0, 0xff, 0x0, 0xff,}, { 0x0, 0xff, 0x0, 0xff, 0x0, 0xff,}, }, [<API key>] = { 0, { 0x0254, 0x0000, 0x0331, 0x0254, 0xff37, 0xfe60, 0x0254, 0x0409, 0x0000, }, { 0xfff0, 0xff80, 0xff80,}, { 0x0, 0x0, 0x0,}, { 0x0, 0xff, 0x0, 0xff, 0x0, 0xff,}, { 0x0, 0xff, 0x0, 0xff, 0x0, 0xff,}, }, [<API key>] = { 0, { 0x0083, 0x0102, 0x0032, 0x1fb5, 0x1f6c, 0x00e1, 0x00e1, 0x1f45, 0x1fdc }, { 0x0, 0x0, 0x0,}, { 0x0010, 0x0080, 0x0080,}, { 0x0, 0xff, 0x0, 0xff, 0x0, 0xff,}, { 0x0010, 0x00eb, 0x0010, 0x00f0, 0x0010, 0x00f0,}, }, [<API key>] = { 0, { 0x0200, 0x0000, 0x0000, 0x0000, 0x0200, 0x0000, 0x0000, 0x0000, 0x0200, }, { 0x0, 0x0, 0x0,}, { 0x0, 0x0, 0x0,}, { 0x0, 0xff, 0x0, 0xff, 0x0, 0xff,}, { 0x0, 0xff, 0x0, 0xff, 0x0, 0xff,}, }, }; #if defined(<API key>) struct mdp_csc_cfg dmb_csc_convert = { #if defined(<API key>) 0, { 0x023e, 0x0000, 0x0331, //287 0x0244, 0xff37, 0xfe60, //290 0x026c, 0x0409, 0x0000, //310 }, { 0xfff0, 0xff80, 0xff80,}, { 0x0, 0x0, 0x0,}, { 0x0, 0xff, 0x0, 0xff, 0x0, 0xff,}, { 0x0, 0xff, 0x0, 0xff, 0x0, 0xff,}, #else 0, { 0x0254, 0x0000, 0x0331, 0x0254, 0xff37, 0xfe60, 0x0254, 0x0409, 0x0000, }, { 0xfff0, 0xff80, 0xff80,}, { 0x0, 0x0, 0x0,}, { 0x0, 0xff, 0x0, 0xff, 0x0, 0xff,}, { 0x0, 0xff, 0x0, 0xff, 0x0, 0xff,}, #endif }; #endif #define CSC_MV_OFF 0x0 #define CSC_BV_OFF 0x2C #define CSC_LV_OFF 0x14 #define CSC_POST_OFF 0xC #define MDSS_BLOCK_DISP_NUM (MDP_BLOCK_MAX - <API key>) #define HIST_WAIT_TIMEOUT(frame) ((75 * HZ * (frame)) / 1000) /* hist collect state */ enum { HIST_UNKNOWN, HIST_IDLE, HIST_RESET, HIST_START, HIST_READY, }; static u32 dither_matrix[16] = { 15, 7, 13, 5, 3, 11, 1, 9, 12, 4, 14, 6, 0, 8, 2, 10}; static u32 dither_depth_map[9] = { 0, 0, 0, 0, 0, 1, 2, 3, 3}; static u32 igc_limited[IGC_LUT_ENTRIES] = { 16777472, 17826064, 18874656, 19923248, 19923248, 20971840, 22020432, 23069024, 24117616, 25166208, 26214800, 26214800, 27263392, 28311984, 29360576, 30409168, 31457760, 32506352, 32506352, 33554944, 34603536, 35652128, 36700720, 37749312, 38797904, 38797904, 39846496, 40895088, 41943680, 42992272, 44040864, 45089456, 45089456, 46138048, 47186640, 48235232, 49283824, 50332416, 51381008, 51381008, 52429600, 53478192, 54526784, 55575376, 56623968, 57672560, 58721152, 58721152, 59769744, 60818336, 61866928, 62915520, 63964112, 65012704, 65012704, 66061296, 67109888, 68158480, 69207072, 70255664, 71304256, 71304256, 72352848, 73401440, 74450032, 75498624, 76547216, 77595808, 77595808, 78644400, 79692992, 80741584, 81790176, 82838768, 83887360, 83887360, 84935952, 85984544, 87033136, 88081728, 89130320, 90178912, 90178912, 91227504, 92276096, 93324688, 94373280, 95421872, 96470464, 96470464, 97519056, 98567648, 99616240, 100664832, 101713424, 102762016, 102762016, 103810608, 104859200, 105907792, 106956384, 108004976, 109053568, 109053568, 110102160, 111150752, 112199344, 113247936, 114296528, 115345120, 115345120, 116393712, 117442304, 118490896, 119539488, 120588080, 121636672, 121636672, 122685264, 123733856, 124782448, 125831040, 126879632, 127928224, 127928224, 128976816, 130025408, 131074000, 132122592, 133171184, 134219776, 135268368, 135268368, 136316960, 137365552, 138414144, 139462736, 140511328, 141559920, 141559920, 142608512, 143657104, 144705696, 145754288, 146802880, 147851472, 147851472, 148900064, 149948656, 150997248, 152045840, 153094432, 154143024, 154143024, 155191616, 156240208, 157288800, 158337392, 159385984, 160434576, 160434576, 161483168, 162531760, 163580352, 164628944, 165677536, 166726128, 166726128, 167774720, 168823312, 169871904, 170920496, 171969088, 173017680, 173017680, 174066272, 175114864, 176163456, 177212048, 178260640, 179309232, 179309232, 180357824, 181406416, 182455008, 183503600, 184552192, 185600784, 185600784, 186649376, 187697968, 188746560, 189795152, 190843744, 191892336, 191892336, 192940928, 193989520, 195038112, 196086704, 197135296, 198183888, 198183888, 199232480, 200281072, 201329664, 202378256, 203426848, 204475440, 204475440, 205524032, 206572624, 207621216, 208669808, 209718400, 210766992, 211815584, 211815584, 212864176, 213912768, 214961360, 216009952, 217058544, 218107136, 218107136, 219155728, 220204320, 221252912, 222301504, 223350096, 224398688, 224398688, 225447280, 226495872, 227544464, 228593056, 229641648, 230690240, 230690240, 231738832, 232787424, 233836016, 234884608, 235933200, 236981792, 236981792, 238030384, 239078976, 240127568, 241176160, 242224752, 243273344, 243273344, 244321936, 245370528, 246419120}; #define GAMUT_T0_SIZE 125 #define GAMUT_T1_SIZE 100 #define GAMUT_T2_SIZE 80 #define GAMUT_T3_SIZE 100 #define GAMUT_T4_SIZE 100 #define GAMUT_T5_SIZE 80 #define GAMUT_T6_SIZE 64 #define GAMUT_T7_SIZE 80 #define <API key> (GAMUT_T0_SIZE + GAMUT_T1_SIZE + \ GAMUT_T2_SIZE + GAMUT_T3_SIZE + GAMUT_T4_SIZE + \ GAMUT_T5_SIZE + GAMUT_T6_SIZE + GAMUT_T7_SIZE) #define MDSS_MDP_PA_SIZE 0xC #define <API key> 0xC #define <API key> 0x3C #define MDSS_MDP_GC_SIZE 0x28 #define MDSS_MDP_PCC_SIZE 0xB8 #define MDSS_MDP_GAMUT_SIZE 0x5C #define <API key> 0x28 #define <API key> 0x88 #define TOTAL_BLEND_STAGES 0x4 #define PP_FLAGS_DIRTY_PA 0x1 #define PP_FLAGS_DIRTY_PCC 0x2 #define PP_FLAGS_DIRTY_IGC 0x4 #define PP_FLAGS_DIRTY_ARGC 0x8 #define <API key> 0x10 #define <API key> 0x20 #define <API key> 0x40 #define <API key> 0x80 #define PP_FLAGS_DIRTY_PGC 0x100 #define <API key> 0x200 #define PP_SSPP 0 #define PP_DSPP 1 #define PP_STS_ENABLE 0x1 #define PP_STS_GAMUT_FIRST 0x2 #define PP_STS_PA_HUE_MASK 0x2 #define PP_STS_PA_SAT_MASK 0x4 #define PP_STS_PA_VAL_MASK 0x8 #define PP_STS_PA_CONT_MASK 0x10 #define <API key> 0x20 #define <API key> 0x40 #define <API key> 0x80 #define <API key> 0x100 #define <API key> 0x200 #define <API key> 0x400 #define <API key> 0x800 #define <API key> 0x1000 #define PP_AD_BAD_HW_NUM 255 #define MDSS_SIDE_NONE 0 #define MDSS_SIDE_LEFT 1 #define MDSS_SIDE_RIGHT 2 #define PP_AD_STATE_INIT 0x2 #define PP_AD_STATE_CFG 0x4 #define PP_AD_STATE_DATA 0x8 #define PP_AD_STATE_RUN 0x10 #define PP_AD_STATE_VSYNC 0x20 #define PP_AD_STATE_BL_LIN 0x40 #define <API key>(st) (((st) & PP_AD_STATE_INIT) &&\ ((st) & PP_AD_STATE_CFG)) #define <API key>(st) (((st) & PP_AD_STATE_INIT) &&\ ((st) & PP_AD_STATE_CFG) &&\ ((st) & PP_AD_STATE_DATA)) #define <API key> 0x2 #define PP_AD_STS_DIRTY_CFG 0x4 #define <API key> 0x8 #define <API key> 0x10 #define <API key> 0x20 #define PP_AD_STS_IS_DIRTY(sts) (((sts) & <API key>) ||\ ((sts) & PP_AD_STS_DIRTY_CFG)) /* Bits 0 and 1 */ #define <API key> (0x03) /* Bits 3 and 7 */ #define <API key> (0x88) /* * Check data by shifting by mode to see if it matches to the * MDSS_AD_INPUT_* bitfields */ #define <API key>(mode, data) ((1 << (mode)) & (data)) #define <API key>(ad) (((ad)->state & PP_AD_STATE_RUN) &&\ ((ad)->cfg.mode == <API key>)) #define <API key>(ad) (((ad)->state & PP_AD_STATE_RUN) &&\ ((ad)->cfg.mode == <API key>)) #define <API key> 32 #define <API key> 112 #define <API key> 8 #define <API key> 2 #define <API key>(ab_val, ib_val) \ { \ .src = MSM_BUS_MASTER_SPDM, \ .dst = <API key>, \ .ab = (ab_val), \ .ib = (ib_val), \ } #define SZ_37_5M (37500000 * 8) static struct msm_bus_vectors mdp_pp_bus_vectors[] = { <API key>(0, 0), <API key>(0, SZ_37_5M), }; static struct msm_bus_paths mdp_pp_bus_usecases[ARRAY_SIZE(mdp_pp_bus_vectors)]; static struct msm_bus_scale_pdata <API key> = { .usecase = mdp_pp_bus_usecases, .num_usecases = ARRAY_SIZE(mdp_pp_bus_usecases), .name = "mdss_pp", }; struct mdss_pp_res_type { /* logical info */ u32 pp_disp_flags[MDSS_BLOCK_DISP_NUM]; u32 igc_lut_c0c1[MDSS_BLOCK_DISP_NUM][IGC_LUT_ENTRIES]; u32 igc_lut_c2[MDSS_BLOCK_DISP_NUM][IGC_LUT_ENTRIES]; struct mdp_ar_gc_lut_data gc_lut_r[MDSS_BLOCK_DISP_NUM][GC_LUT_SEGMENTS]; struct mdp_ar_gc_lut_data gc_lut_g[MDSS_BLOCK_DISP_NUM][GC_LUT_SEGMENTS]; struct mdp_ar_gc_lut_data gc_lut_b[MDSS_BLOCK_DISP_NUM][GC_LUT_SEGMENTS]; u32 enhist_lut[MDSS_BLOCK_DISP_NUM][ENHIST_LUT_ENTRIES]; struct mdp_pa_cfg pa_disp_cfg[MDSS_BLOCK_DISP_NUM]; struct mdp_pa_v2_data pa_v2_disp_cfg[MDSS_BLOCK_DISP_NUM]; u32 <API key>[MDSS_BLOCK_DISP_NUM][<API key>]; u32 <API key>[MDSS_BLOCK_DISP_NUM][<API key>]; struct mdp_pcc_cfg_data pcc_disp_cfg[MDSS_BLOCK_DISP_NUM]; struct mdp_igc_lut_data igc_disp_cfg[MDSS_BLOCK_DISP_NUM]; struct mdp_pgc_lut_data argc_disp_cfg[MDSS_BLOCK_DISP_NUM]; struct mdp_pgc_lut_data pgc_disp_cfg[MDSS_BLOCK_DISP_NUM]; struct mdp_hist_lut_data enhist_disp_cfg[MDSS_BLOCK_DISP_NUM]; struct mdp_dither_cfg_data dither_disp_cfg[MDSS_BLOCK_DISP_NUM]; struct mdp_gamut_cfg_data gamut_disp_cfg[MDSS_BLOCK_DISP_NUM]; uint16_t gamut_tbl[MDSS_BLOCK_DISP_NUM][<API key>]; u32 hist_data[MDSS_BLOCK_DISP_NUM][HIST_V_SIZE]; struct pp_sts_type pp_disp_sts[MDSS_BLOCK_DISP_NUM]; /* physical info */ struct pp_hist_col_info dspp_hist[MDSS_MDP_MAX_DSPP]; }; #ifdef CONFIG_MACH_LGE uint32_t igc_Table_RGB[256] = { 4080 , 4064 , 4048 , 4032 , 4016 , 4000 , 3984 , 3968 , 3952 , 3936 , 3920 , 3904 , 3888 , 3872 , 3856 , 3840 , 3824 , 3808 , 3792 , 3776 , 3760 , 3744 , 3728 , 3712 , 3696 , 3680 , 3664 , 3648 , 3632 , 3616 , 3600 , 3584 , 3568 , 3552 , 3536 , 3520 , 3504 , 3488 , 3472 , 3456 , 3440 , 3424 , 3408 , 3392 , 3376 , 3360 , 3344 , 3328 , 3312 , 3296 , 3280 , 3264 , 3248 , 3232 , 3216 , 3200 , 3184 , 3168 , 3152 , 3136 , 3120 , 3104 , 3088 , 3072 , 3056 , 3040 , 3024 , 3008 , 2992 , 2976 , 2960 , 2944 , 2928 , 2912 , 2896 , 2880 , 2864 , 2848 , 2832 , 2816 , 2800 , 2784 , 2768 , 2752 , 2736 , 2720 , 2704 , 2688 , 2672 , 2656 , 2640 , 2624 , 2608 , 2592 , 2576 , 2560 , 2544 , 2528 , 2512 , 2496 , 2480 , 2464 , 2448 , 2432 , 2416 , 2400 , 2384 , 2368 , 2352 , 2336 , 2320 , 2304 , 2288 , 2272 , 2256 , 2240 , 2224 , 2208 , 2192 , 2176 , 2160 , 2144 , 2128 , 2112 , 2096 , 2080 , 2064 , 2048 , 2032 , 2016 , 2000 , 1984 , 1968 , 1952 , 1936 , 1920 , 1904 , 1888 , 1872 , 1856 , 1840 , 1824 , 1808 , 1792 , 1776 , 1760 , 1744 , 1728 , 1712 , 1696 , 1680 , 1664 , 1648 , 1632 , 1616 , 1600 , 1584 , 1568 , 1552 , 1536 , 1520 , 1504 , 1488 , 1472 , 1456 , 1440 , 1424 , 1408 , 1392 , 1376 , 1360 , 1344 , 1328 , 1312 , 1296 , 1280 , 1264 , 1248 , 1232 , 1216 , 1200 , 1184 , 1168 , 1152 , 1136 , 1120 , 1104 , 1088 , 1072 , 1056 , 1040 , 1024 , 1008 , 992 , 976 , 960 , 944 , 928 , 912 , 896 , 880 , 864 , 848 , 832 , 816 , 800 , 784 , 768 , 752 , 736 , 720 , 704 , 688 , 672 , 656 , 640 , 624 , 608 , 592 , 576 , 560 , 544 , 528 , 512 , 496 , 480 , 464 , 448 , 432 , 416 , 400 , 384 , 368 , 352 , 336 , 320 , 304 , 288 , 272 , 256 , 240 , 224 , 208 , 192 , 176 , 160 , 144 , 128 , 112 , 96 , 80 , 64 , 48 , 32 , 16 , 0 }; int igc_c0_c1[256] = {0,}; int igc_c2[256] = {0,}; #endif static DEFINE_MUTEX(mdss_pp_mutex); static struct mdss_pp_res_type *mdss_pp_res; #if defined(<API key>) static int dmb_status = 0; /* on - 1, off - 0 */ int pp_set_dmb_status(int flag) { dmb_status = flag; return 0; } #endif static u32 pp_hist_read(char __iomem *v_addr, struct pp_hist_col_info *hist_info); static int pp_histogram_setup(u32 *op, u32 block, struct mdss_mdp_mixer *mix); static int <API key>(struct pp_hist_col_info *hist_info, u32 done_bit, char __iomem *ctl_base); static void pp_update_pcc_regs(char __iomem *addr, struct mdp_pcc_cfg_data *cfg_ptr); static void pp_update_igc_lut(struct mdp_igc_lut_data *cfg, char __iomem *addr, u32 blk_idx); static void <API key>(char __iomem *addr, struct mdp_ar_gc_lut_data *lut_data, uint8_t num_stages); static void pp_update_argc_lut(char __iomem *addr, struct mdp_pgc_lut_data *config); static void pp_update_hist_lut(char __iomem *base, struct mdp_hist_lut_data *cfg); static int <API key>(struct mdp_gamut_cfg_data *config); static void pp_gamut_config(struct mdp_gamut_cfg_data *gamut_cfg, char __iomem *base, struct pp_sts_type *pp_sts); static void pp_pa_config(unsigned long flags, char __iomem *addr, struct pp_sts_type *pp_sts, struct mdp_pa_cfg *pa_config); static void pp_pa_v2_config(unsigned long flags, char __iomem *addr, struct pp_sts_type *pp_sts, struct mdp_pa_v2_data *pa_v2_config, int mdp_location); static void pp_pcc_config(unsigned long flags, char __iomem *addr, struct pp_sts_type *pp_sts, struct mdp_pcc_cfg_data *pcc_config); static void pp_igc_config(unsigned long flags, char __iomem *addr, struct pp_sts_type *pp_sts, struct mdp_igc_lut_data *igc_config, u32 pipe_num); static void pp_enhist_config(unsigned long flags, char __iomem *addr, struct pp_sts_type *pp_sts, struct mdp_hist_lut_data *enhist_cfg); static void pp_dither_config(char __iomem *addr, struct pp_sts_type *pp_sts, struct mdp_dither_cfg_data *dither_cfg); static void <API key>(struct mdss_mdp_ctl *ctl, u32 num, struct pp_sts_type *pp_sts, int mdp_rev, u32 *opmode); static void pp_sharp_config(char __iomem *addr, struct pp_sts_type *pp_sts, struct mdp_sharp_cfg *sharp_config); static void <API key>(struct pp_sts_type *pp_sts, u32 *opmode); static int <API key>(struct mdp_pa_v2_cfg_data *pa_v2_config, u32 disp_num); static void <API key>(char __iomem *addr, struct mdp_pa_v2_data *pa_config); static void <API key>(char __iomem *addr, struct mdp_pa_v2_data *pa_v2_config); static void <API key>(char __iomem *addr, struct mdp_pa_mem_col_cfg *cfg); static void <API key>(char __iomem *addr, struct mdp_pa_v2_data *pa_v2_config); static void pp_update_pa_v2_sts(struct pp_sts_type *pp_sts, struct mdp_pa_v2_data *pa_v2_config); static int pp_read_pa_v2_regs(char __iomem *addr, struct mdp_pa_v2_data *pa_v2_config, u32 disp_num); static void <API key>(char __iomem *addr, struct mdp_pa_mem_col_cfg *mem_col_cfg); static int mdss_ad_init_checks(struct msm_fb_data_type *mfd); static int mdss_mdp_get_ad(struct msm_fb_data_type *mfd, struct mdss_ad_info **ad); static int pp_update_ad_input(struct msm_fb_data_type *mfd); static void pp_ad_vsync_handler(struct mdss_mdp_ctl *ctl, ktime_t t); static void pp_ad_cfg_write(struct mdss_mdp_ad *ad_hw, struct mdss_ad_info *ad); static void pp_ad_init_write(struct mdss_mdp_ad *ad_hw, struct mdss_ad_info *ad, struct mdss_mdp_ctl *ctl); static void pp_ad_input_write(struct mdss_mdp_ad *ad_hw, struct mdss_ad_info *ad); static int pp_ad_setup_hw_nums(struct msm_fb_data_type *mfd, struct mdss_ad_info *ad); static void pp_ad_bypass_config(struct mdss_ad_info *ad, struct mdss_mdp_ctl *ctl, u32 num, u32 *opmode); static int mdss_mdp_ad_setup(struct msm_fb_data_type *mfd); static void pp_ad_cfg_lut(char __iomem *addr, u32 *data); static int pp_num_to_side(struct mdss_mdp_ctl *ctl, u32 num); static inline bool pp_sts_is_enabled(u32 sts, int side); static inline void <API key>(u32 *sts, u32 bits); static u32 last_sts, last_state; int <API key>(u32 block, u32 blk_idx, u32 tbl_idx, struct mdp_csc_cfg *data) { int i, ret = 0; char __iomem *base, *addr; u32 val = 0; struct mdss_data_type *mdata; struct mdss_mdp_pipe *pipe; struct mdss_mdp_ctl *ctl; if (data == NULL) { pr_err("no csc matrix specified\n"); return -EINVAL; } mdata = mdss_mdp_get_mdata(); switch (block) { case MDSS_MDP_BLOCK_SSPP: if (blk_idx < mdata->nvig_pipes) { pipe = mdata->vig_pipes + blk_idx; base = pipe->base; if (tbl_idx == 1) base += <API key>; else base += <API key>; } else { ret = -EINVAL; } break; case MDSS_MDP_BLOCK_WB: if (blk_idx < mdata->nctl) { ctl = mdata->ctl_off + blk_idx; base = ctl->wb_base + <API key>; } else { ret = -EINVAL; } break; default: ret = -EINVAL; break; } if (ret != 0) { pr_err("unsupported block id for csc\n"); return ret; } addr = base + CSC_MV_OFF; for (i = 0; i < 9; i++) { if (i & 0x1) { val |= data->csc_mv[i] << 16; writel_relaxed(val, addr); addr += sizeof(u32 *); } else { val = data->csc_mv[i]; } } writel_relaxed(val, addr); /* COEFF_33 */ addr = base + CSC_BV_OFF; for (i = 0; i < 3; i++) { writel_relaxed(data->csc_pre_bv[i], addr); writel_relaxed(data->csc_post_bv[i], addr + CSC_POST_OFF); addr += sizeof(u32 *); } addr = base + CSC_LV_OFF; for (i = 0; i < 6; i += 2) { val = (data->csc_pre_lv[i] << 8) | data->csc_pre_lv[i+1]; writel_relaxed(val, addr); val = (data->csc_post_lv[i] << 8) | data->csc_post_lv[i+1]; writel_relaxed(val, addr + CSC_POST_OFF); addr += sizeof(u32 *); } return ret; } int mdss_mdp_csc_setup(u32 block, u32 blk_idx, u32 tbl_idx, u32 csc_type) { struct mdp_csc_cfg *data; if (csc_type >= MDSS_MDP_MAX_CSC) { pr_err("invalid csc matrix index %d\n", csc_type); return -ERANGE; } pr_debug("csc type=%d blk=%d idx=%d tbl=%d\n", csc_type, block, blk_idx, tbl_idx); data = &mdp_csc_convert[csc_type]; return <API key>(block, blk_idx, tbl_idx, data); } static void pp_gamut_config(struct mdp_gamut_cfg_data *gamut_cfg, char __iomem *base, struct pp_sts_type *pp_sts) { char __iomem *addr; int i, j; if (gamut_cfg->flags & MDP_PP_OPS_WRITE) { addr = base + <API key>; for (i = 0; i < MDP_GAMUT_TABLE_NUM; i++) { for (j = 0; j < gamut_cfg->tbl_size[i]; j++) writel_relaxed((u32)gamut_cfg->r_tbl[i][j], addr); addr += 4; } for (i = 0; i < MDP_GAMUT_TABLE_NUM; i++) { for (j = 0; j < gamut_cfg->tbl_size[i]; j++) writel_relaxed((u32)gamut_cfg->g_tbl[i][j], addr); addr += 4; } for (i = 0; i < MDP_GAMUT_TABLE_NUM; i++) { for (j = 0; j < gamut_cfg->tbl_size[i]; j++) writel_relaxed((u32)gamut_cfg->b_tbl[i][j], addr); addr += 4; } if (gamut_cfg->gamut_first) pp_sts->gamut_sts |= PP_STS_GAMUT_FIRST; } if (gamut_cfg->flags & MDP_PP_OPS_DISABLE) pp_sts->gamut_sts &= ~PP_STS_ENABLE; else if (gamut_cfg->flags & MDP_PP_OPS_ENABLE) pp_sts->gamut_sts |= PP_STS_ENABLE; <API key>(&pp_sts->gamut_sts, gamut_cfg->flags); } static void pp_pa_config(unsigned long flags, char __iomem *addr, struct pp_sts_type *pp_sts, struct mdp_pa_cfg *pa_config) { if (flags & PP_FLAGS_DIRTY_PA) { if (pa_config->flags & MDP_PP_OPS_WRITE) { writel_relaxed(pa_config->hue_adj, addr); addr += 4; writel_relaxed(pa_config->sat_adj, addr); addr += 4; writel_relaxed(pa_config->val_adj, addr); addr += 4; writel_relaxed(pa_config->cont_adj, addr); } if (pa_config->flags & MDP_PP_OPS_DISABLE) pp_sts->pa_sts &= ~PP_STS_ENABLE; else if (pa_config->flags & MDP_PP_OPS_ENABLE) pp_sts->pa_sts |= PP_STS_ENABLE; } } static void pp_pa_v2_config(unsigned long flags, char __iomem *addr, struct pp_sts_type *pp_sts, struct mdp_pa_v2_data *pa_v2_config, int mdp_location) { if ((flags & PP_FLAGS_DIRTY_PA) && (pa_v2_config->flags & MDP_PP_OPS_WRITE)) { <API key>(addr, pa_v2_config); /* Update PA DSPP Regs */ if (mdp_location == PP_DSPP) { addr += 0x10; <API key>(addr, pa_v2_config); addr += 0xC; <API key>(addr, pa_v2_config); } else if (mdp_location == PP_SSPP) { /* Update PA SSPP Regs */ addr -= <API key>; addr += <API key>; <API key>(addr, pa_v2_config); } pp_update_pa_v2_sts(pp_sts, pa_v2_config); } } static void <API key>(char __iomem *addr, struct mdp_pa_v2_data *pa_v2_config) { if (pa_v2_config->flags & <API key>) writel_relaxed(pa_v2_config->global_hue_adj, addr); addr += 4; if (pa_v2_config->flags & <API key>) /* Sat Global Adjust reg includes Sat Threshold */ writel_relaxed(pa_v2_config->global_sat_adj, addr); addr += 4; if (pa_v2_config->flags & <API key>) writel_relaxed(pa_v2_config->global_val_adj, addr); addr += 4; if (pa_v2_config->flags & <API key>) writel_relaxed(pa_v2_config->global_cont_adj, addr); } static void <API key>(char __iomem *addr, struct mdp_pa_v2_data *pa_v2_config) { /* Update skin zone memory color registers */ if (pa_v2_config->flags & <API key>) <API key>(addr, &pa_v2_config->skin_cfg); addr += 0x14; /* Update sky zone memory color registers */ if (pa_v2_config->flags & <API key>) <API key>(addr, &pa_v2_config->sky_cfg); addr += 0x14; /* Update foliage zone memory color registers */ if (pa_v2_config->flags & <API key>) <API key>(addr, &pa_v2_config->fol_cfg); } static void <API key>(char __iomem *addr, struct mdp_pa_mem_col_cfg *cfg) { pr_debug("ADDR: 0x%x, P0: 0x%x\n", (u32)addr, cfg->color_adjust_p0); writel_relaxed(cfg->color_adjust_p0, addr); addr += 4; pr_debug("ADDR: 0x%x, P1: 0x%x\n", (u32)addr, cfg->color_adjust_p1); writel_relaxed(cfg->color_adjust_p1, addr); addr += 4; pr_debug("ADDR: 0x%x, HUE REGION: 0x%x\n", (u32)addr, cfg->hue_region); writel_relaxed(cfg->hue_region, addr); addr += 4; pr_debug("ADDR: 0x%x, SAT REGION: 0x%x\n", (u32)addr, cfg->sat_region); writel_relaxed(cfg->sat_region, addr); addr += 4; pr_debug("ADDR: 0x%x, VAL REGION: 0x%x\n", (u32)addr, cfg->val_region); writel_relaxed(cfg->val_region, addr); } static void <API key>(char __iomem *addr, struct mdp_pa_v2_data *pa_v2_config) { int i; u32 data; /* Update six zone memory color registers */ if (pa_v2_config->flags & <API key>) { addr += 4; writel_relaxed(pa_v2_config->six_zone_curve_p1[0], addr); addr -= 4; /* Index Update to trigger auto-incrementing LUT accesses */ data = (1 << 26); writel_relaxed((pa_v2_config->six_zone_curve_p0[0] & 0xFFF) | data, addr); /* Remove Index Update */ for (i = 1; i < <API key>; i++) { addr += 4; writel_relaxed(pa_v2_config->six_zone_curve_p1[i], addr); addr -= 4; writel_relaxed(pa_v2_config->six_zone_curve_p0[i] & 0xFFF, addr); } addr += 8; writel_relaxed(pa_v2_config->six_zone_thresh, addr); } } static void pp_update_pa_v2_sts(struct pp_sts_type *pp_sts, struct mdp_pa_v2_data *pa_v2_config) { pp_sts->pa_sts = 0; /* PA STS update */ if (pa_v2_config->flags & MDP_PP_OPS_ENABLE) pp_sts->pa_sts |= PP_STS_ENABLE; else pp_sts->pa_sts &= ~PP_STS_ENABLE; /* Global HSV STS update */ if (pa_v2_config->flags & MDP_PP_PA_HUE_MASK) pp_sts->pa_sts |= PP_STS_PA_HUE_MASK; if (pa_v2_config->flags & MDP_PP_PA_SAT_MASK) pp_sts->pa_sts |= PP_STS_PA_SAT_MASK; if (pa_v2_config->flags & MDP_PP_PA_VAL_MASK) pp_sts->pa_sts |= PP_STS_PA_VAL_MASK; if (pa_v2_config->flags & MDP_PP_PA_CONT_MASK) pp_sts->pa_sts |= PP_STS_PA_CONT_MASK; if (pa_v2_config->flags & <API key>) pp_sts->pa_sts |= <API key>; if (pa_v2_config->flags & <API key>) pp_sts->pa_sts |= <API key>; /* Memory Color STS update */ if (pa_v2_config->flags & <API key>) pp_sts->pa_sts |= <API key>; if (pa_v2_config->flags & <API key>) pp_sts->pa_sts |= <API key>; if (pa_v2_config->flags & <API key>) pp_sts->pa_sts |= <API key>; /* Six Zone STS update */ if (pa_v2_config->flags & <API key>) pp_sts->pa_sts |= <API key>; if (pa_v2_config->flags & <API key>) pp_sts->pa_sts |= <API key>; if (pa_v2_config->flags & <API key>) pp_sts->pa_sts |= <API key>; <API key>(&pp_sts->pa_sts, pa_v2_config->flags); } static void pp_pcc_config(unsigned long flags, char __iomem *addr, struct pp_sts_type *pp_sts, struct mdp_pcc_cfg_data *pcc_config) { if (flags & PP_FLAGS_DIRTY_PCC) { if (pcc_config->ops & MDP_PP_OPS_WRITE) pp_update_pcc_regs(addr, pcc_config); if (pcc_config->ops & MDP_PP_OPS_DISABLE) pp_sts->pcc_sts &= ~PP_STS_ENABLE; else if (pcc_config->ops & MDP_PP_OPS_ENABLE) pp_sts->pcc_sts |= PP_STS_ENABLE; <API key>(&pp_sts->pcc_sts, pcc_config->ops); } } static void pp_igc_config(unsigned long flags, char __iomem *addr, struct pp_sts_type *pp_sts, struct mdp_igc_lut_data *igc_config, u32 pipe_num) { u32 tbl_idx; if (flags & PP_FLAGS_DIRTY_IGC) { if (igc_config->ops & MDP_PP_OPS_WRITE) pp_update_igc_lut(igc_config, addr, pipe_num); if (igc_config->ops & <API key>) { pp_sts->pcc_sts |= PP_STS_ENABLE; tbl_idx = 1; } else if (igc_config->ops & <API key>) { pp_sts->pcc_sts |= PP_STS_ENABLE; tbl_idx = 2; } else { tbl_idx = 0; } pp_sts->igc_tbl_idx = tbl_idx; if (igc_config->ops & MDP_PP_OPS_DISABLE) pp_sts->igc_sts &= ~PP_STS_ENABLE; else if (igc_config->ops & MDP_PP_OPS_ENABLE) pp_sts->igc_sts |= PP_STS_ENABLE; <API key>(&pp_sts->igc_sts, igc_config->ops); } } static void pp_enhist_config(unsigned long flags, char __iomem *addr, struct pp_sts_type *pp_sts, struct mdp_hist_lut_data *enhist_cfg) { if (flags & <API key>) { if (enhist_cfg->ops & MDP_PP_OPS_WRITE) pp_update_hist_lut(addr, enhist_cfg); if (enhist_cfg->ops & MDP_PP_OPS_DISABLE) pp_sts->enhist_sts &= ~PP_STS_ENABLE; else if (enhist_cfg->ops & MDP_PP_OPS_ENABLE) pp_sts->enhist_sts |= PP_STS_ENABLE; } } /*the below function doesn't do error checking on the input params*/ static void pp_sharp_config(char __iomem *addr, struct pp_sts_type *pp_sts, struct mdp_sharp_cfg *sharp_config) { if (sharp_config->flags & MDP_PP_OPS_WRITE) { writel_relaxed(sharp_config->strength, addr); addr += 4; writel_relaxed(sharp_config->edge_thr, addr); addr += 4; writel_relaxed(sharp_config->smooth_thr, addr); addr += 4; writel_relaxed(sharp_config->noise_thr, addr); } if (sharp_config->flags & MDP_PP_OPS_DISABLE) pp_sts->sharp_sts &= ~PP_STS_ENABLE; else if (sharp_config->flags & MDP_PP_OPS_ENABLE) pp_sts->sharp_sts |= PP_STS_ENABLE; } static int pp_vig_pipe_setup(struct mdss_mdp_pipe *pipe, u32 *op) { u32 opmode = 0; unsigned long flags = 0; char __iomem *offset; struct mdss_data_type *mdata; pr_debug("pnum=%x\n", pipe->num); mdata = mdss_mdp_get_mdata(); if ((pipe->flags & <API key>) && (pipe->pp_cfg.config_ops & <API key>)) { opmode |= !!(pipe->pp_cfg.csc_cfg.flags & MDP_CSC_FLAG_ENABLE) << 17; opmode |= !!(pipe->pp_cfg.csc_cfg.flags & MDP_CSC_FLAG_YUV_IN) << 18; opmode |= !!(pipe->pp_cfg.csc_cfg.flags & <API key>) << 19; /* * TODO: Allow pipe to be programmed whenever new CSC is * applied (i.e. dirty bit) */ if (pipe->play_cnt == 0) <API key>(MDSS_MDP_BLOCK_SSPP, pipe->num, 1, &pipe->pp_cfg.csc_cfg); } else { if (pipe->src_fmt->is_yuv) opmode |= (0 << 19) | /* DST_DATA=RGB */ (1 << 18) | /* SRC_DATA=YCBCR */ (1 << 17); /* CSC_1_EN */ /* * TODO: Needs to be part of dirty bit logic: if there is a * previously configured pipe need to re-configure CSC matrix */ if (pipe->play_cnt == 0) { #if !defined(<API key>) mdss_mdp_csc_setup(MDSS_MDP_BLOCK_SSPP, pipe->num, 1, <API key>); #else if (dmb_status == 1) { <API key>(MDSS_MDP_BLOCK_SSPP, pipe->num, 1, &dmb_csc_convert); } else { mdss_mdp_csc_setup(MDSS_MDP_BLOCK_SSPP, pipe->num, 1, <API key>); } #endif } } pp_histogram_setup(&opmode, MDSS_PP_SSPP_CFG | pipe->num, pipe->mixer); if (pipe->flags & <API key>) { if ((pipe->pp_cfg.config_ops & <API key>) && (mdata->mdp_rev < MDSS_MDP_HW_REV_103)) { flags = PP_FLAGS_DIRTY_PA; pp_pa_config(flags, pipe->base + <API key>, &pipe->pp_res.pp_sts, &pipe->pp_cfg.pa_cfg); if (pipe->pp_res.pp_sts.pa_sts & PP_STS_ENABLE) opmode |= <API key>; } if ((pipe->pp_cfg.config_ops & <API key>) && (mdata->mdp_rev >= MDSS_MDP_HW_REV_103)) { flags = PP_FLAGS_DIRTY_PA; pp_pa_v2_config(flags, pipe->base + <API key>, &pipe->pp_res.pp_sts, &pipe->pp_cfg.pa_v2_cfg, PP_SSPP); <API key>(&pipe->pp_res.pp_sts, &opmode); if (pipe->pp_res.pp_sts.pa_sts & PP_STS_ENABLE) opmode |= <API key>; } if (pipe->pp_cfg.config_ops & <API key>) { pp_enhist_config(<API key>, pipe->base + <API key>, &pipe->pp_res.pp_sts, &pipe->pp_cfg.hist_lut_cfg); } } if (pipe->pp_res.pp_sts.enhist_sts & PP_STS_ENABLE) { /* Enable HistLUT and PA */ opmode |= BIT(10) | BIT(4); if (!(pipe->pp_res.pp_sts.pa_sts & PP_STS_ENABLE)) { /* Program default value */ offset = pipe->base + <API key>; writel_relaxed(0, offset); writel_relaxed(0, offset + 4); writel_relaxed(0, offset + 8); writel_relaxed(0, offset + 12); } } *op |= opmode; return 0; } static void <API key>(struct pp_sts_type *pp_sts, u32 *opmode) { if (pp_sts->pa_sts & PP_STS_PA_HUE_MASK) *opmode |= <API key>; if (pp_sts->pa_sts & PP_STS_PA_SAT_MASK) *opmode |= <API key>; if (pp_sts->pa_sts & PP_STS_PA_VAL_MASK) *opmode |= <API key>; if (pp_sts->pa_sts & PP_STS_PA_CONT_MASK) *opmode |= <API key>; if (pp_sts->pa_sts & <API key>) *opmode |= <API key>; if (pp_sts->pa_sts & <API key>) *opmode |= <API key>; if (pp_sts->pa_sts & <API key>) *opmode |= <API key>; if (pp_sts->pa_sts & <API key>) *opmode |= <API key>; if (pp_sts->pa_sts & <API key>) *opmode |= <API key>; } static int <API key>(struct mdss_mdp_pipe *pipe) { u32 scale_config = 0; int init_phasex = 0, init_phasey = 0; int phasex_step = 0, phasey_step = 0; u32 chroma_sample; u32 filter_mode; struct mdss_data_type *mdata; u32 src_w, src_h; pr_debug("pipe=%d, change pxl ext=%d\n", pipe->num, pipe->scale.enable_pxl_ext); mdata = mdss_mdp_get_mdata(); if (mdata->mdp_rev >= MDSS_MDP_HW_REV_102 && pipe->src_fmt->is_yuv) filter_mode = <API key>; else filter_mode = <API key>; if (pipe->type == <API key>) { if (pipe->dst.h != pipe->src.h || pipe->dst.w != pipe->src.w) { pr_err("no scaling supported on dma pipe\n"); return -EINVAL; } else { return 0; } } src_w = pipe->src.w >> pipe->horz_deci; src_h = pipe->src.h >> pipe->vert_deci; chroma_sample = pipe->src_fmt->chroma_sample; if (pipe->flags & <API key>) { if (chroma_sample == <API key>) chroma_sample = <API key>; else if (chroma_sample == <API key>) chroma_sample = <API key>; } if (!(pipe->pp_cfg.config_ops & <API key>)) { pipe->pp_cfg.sharp_cfg.flags = MDP_PP_OPS_ENABLE | MDP_PP_OPS_WRITE; pipe->pp_cfg.sharp_cfg.strength = <API key>; pipe->pp_cfg.sharp_cfg.edge_thr = <API key>; pipe->pp_cfg.sharp_cfg.smooth_thr = <API key>; pipe->pp_cfg.sharp_cfg.noise_thr = <API key>; } if ((pipe->src_fmt->is_yuv) && !((pipe->dst.w < src_w) || (pipe->dst.h < src_h))) { pp_sharp_config(pipe->base + <API key>, &pipe->pp_res.pp_sts, &pipe->pp_cfg.sharp_cfg); } if ((src_h != pipe->dst.h) || (pipe->pp_res.pp_sts.sharp_sts & PP_STS_ENABLE) || (chroma_sample == MDSS_MDP_CHROMA_420) || (chroma_sample == <API key>) || pipe->scale.enable_pxl_ext) { pr_debug("scale y - src_h=%d dst_h=%d\n", src_h, pipe->dst.h); if ((src_h / MAX_DOWNSCALE_RATIO) > pipe->dst.h) { pr_err("too much downscaling height=%d->%d", src_h, pipe->dst.h); return -EINVAL; } scale_config |= MDSS_MDP_SCALEY_EN; phasey_step = pipe->scale.phase_step_y[0]; init_phasey = pipe->scale.init_phase_y[0]; if (pipe->type == <API key>) { u32 chroma_shift = 0; if (!pipe->vert_deci && ((chroma_sample == MDSS_MDP_CHROMA_420) || (chroma_sample == <API key>))) chroma_shift = 1; /* 2x upsample chroma */ if (src_h <= pipe->dst.h) scale_config |= /* G/Y, A */ (filter_mode << 10) | (<API key> << 18); else scale_config |= /* G/Y, A */ (<API key> << 10) | (<API key> << 18); if ((src_h >> chroma_shift) <= pipe->dst.h) scale_config |= /* CrCb */ (<API key> << 14); else scale_config |= /* CrCb */ (<API key> << 14); writel_relaxed(init_phasey, pipe->base + <API key>); writel_relaxed(phasey_step >> chroma_shift, pipe->base + <API key>); } else { if (src_h <= pipe->dst.h) scale_config |= /* RGB, A */ (<API key> << 10) | (<API key> << 18); else scale_config |= /* RGB, A */ (<API key> << 10) | (<API key> << 18); } } if ((src_w != pipe->dst.w) || (pipe->pp_res.pp_sts.sharp_sts & PP_STS_ENABLE) || (chroma_sample == MDSS_MDP_CHROMA_420) || (chroma_sample == <API key>) || pipe->scale.enable_pxl_ext) { pr_debug("scale x - src_w=%d dst_w=%d\n", src_w, pipe->dst.w); if ((src_w / MAX_DOWNSCALE_RATIO) > pipe->dst.w) { pr_err("too much downscaling width=%d->%d", src_w, pipe->dst.w); return -EINVAL; } scale_config |= MDSS_MDP_SCALEX_EN; init_phasex = pipe->scale.init_phase_x[0]; phasex_step = pipe->scale.phase_step_x[0]; if (pipe->type == <API key>) { u32 chroma_shift = 0; if (!pipe->horz_deci && ((chroma_sample == MDSS_MDP_CHROMA_420) || (chroma_sample == <API key>))) chroma_shift = 1; /* 2x upsample chroma */ if (src_w <= pipe->dst.w) scale_config |= /* G/Y, A */ (filter_mode << 8) | (<API key> << 16); else scale_config |= /* G/Y, A */ (<API key> << 8) | (<API key> << 16); if ((src_w >> chroma_shift) <= pipe->dst.w) scale_config |= /* CrCb */ (<API key> << 12); else scale_config |= /* CrCb */ (<API key> << 12); writel_relaxed(init_phasex, pipe->base + <API key>); writel_relaxed(phasex_step >> chroma_shift, pipe->base + <API key>); } else { if (src_w <= pipe->dst.w) scale_config |= /* RGB, A */ (<API key> << 8) | (<API key> << 16); else scale_config |= /* RGB, A */ (<API key> << 8) | (<API key> << 16); } } if (pipe->scale.enable_pxl_ext && pipe->type == <API key>) { /*program x,y initial phase and phase step*/ writel_relaxed(pipe->scale.init_phase_x[0], pipe->base + <API key>); writel_relaxed(pipe->scale.phase_step_x[0], pipe->base + <API key>); writel_relaxed(pipe->scale.init_phase_x[1], pipe->base + <API key>); writel_relaxed(pipe->scale.phase_step_x[1], pipe->base + <API key>); writel_relaxed(pipe->scale.init_phase_y[0], pipe->base + <API key>); writel_relaxed(pipe->scale.phase_step_y[0], pipe->base + <API key>); writel_relaxed(pipe->scale.init_phase_y[1], pipe->base + <API key>); writel_relaxed(pipe->scale.phase_step_y[1], pipe->base + <API key>); /*program pixel extn values for the SSPP*/ <API key>(pipe); } else if (pipe->type == <API key>) { writel_relaxed(phasex_step, pipe->base + <API key>); writel_relaxed(phasey_step, pipe->base + <API key>); writel_relaxed(init_phasex, pipe->base + <API key>); writel_relaxed(init_phasey, pipe->base + <API key>); } else { writel_relaxed(phasex_step, pipe->base + <API key>); writel_relaxed(phasey_step, pipe->base + <API key>); } writel_relaxed(scale_config, pipe->base + <API key>); return 0; } int <API key>(struct mdss_mdp_pipe *pipe, u32 *op) { int ret = 0; if (!pipe) return -ENODEV; ret = <API key>(pipe); if (ret) return -EINVAL; if (pipe->type == <API key>) ret = pp_vig_pipe_setup(pipe, op); return ret; } void <API key>(struct mdss_mdp_pipe *pipe) { u32 done_bit; struct pp_hist_col_info *hist_info; char __iomem *ctl_base; if (!pipe && pipe->pp_res.hist.col_en) { done_bit = 3 << (pipe->num * 4); hist_info = &pipe->pp_res.hist; ctl_base = pipe->base + <API key>; <API key>(hist_info, done_bit, ctl_base); } memset(&pipe->pp_cfg, 0, sizeof(struct <API key>)); memset(&pipe->pp_res, 0, sizeof(struct mdss_pipe_pp_res)); } int <API key>(struct mdss_mdp_pipe *pipe, u32 *op) { int ret = 0; unsigned long flags = 0; char __iomem *pipe_base; u32 pipe_num; struct mdss_data_type *mdata = mdss_mdp_get_mdata(); if (pipe == NULL) return -EINVAL; /* * TODO: should this function be responsible for masking multiple * pipes to be written in dual pipe case? * if so, requires rework of update_igc_lut */ switch (pipe->type) { case <API key>: pipe_base = mdata->mdp_base + <API key>; pipe_num = pipe->num - MDSS_MDP_SSPP_VIG0; break; case <API key>: pipe_base = mdata->mdp_base + <API key>; pipe_num = pipe->num - MDSS_MDP_SSPP_RGB0; break; case <API key>: pipe_base = mdata->mdp_base + <API key>; pipe_num = pipe->num - MDSS_MDP_SSPP_DMA0; break; default: return -EINVAL; } if (pipe->pp_cfg.config_ops & <API key>) { flags |= PP_FLAGS_DIRTY_IGC; pp_igc_config(flags, pipe_base, &pipe->pp_res.pp_sts, &pipe->pp_cfg.igc_cfg, pipe_num); } if (pipe->pp_res.pp_sts.igc_sts & PP_STS_ENABLE) *op |= (1 << 16); /* IGC_LUT_EN */ return ret; } static int pp_mixer_setup(u32 disp_num, struct mdss_mdp_mixer *mixer) { u32 flags, dspp_num, opmode = 0; struct mdp_pgc_lut_data *pgc_config; struct pp_sts_type *pp_sts; struct mdss_mdp_ctl *ctl; char __iomem *addr; dspp_num = mixer->num; if (!mixer || !mixer->ctl) return -EINVAL; ctl = mixer->ctl; /* no corresponding dspp */ if ((mixer->type != <API key>) || (dspp_num >= MDSS_MDP_MAX_DSPP)) return 0; if (disp_num < MDSS_BLOCK_DISP_NUM) flags = mdss_pp_res->pp_disp_flags[disp_num]; else flags = 0; pp_sts = &mdss_pp_res->pp_disp_sts[disp_num]; /* GC_LUT is in layer mixer */ if (flags & PP_FLAGS_DIRTY_ARGC) { pgc_config = &mdss_pp_res->argc_disp_cfg[disp_num]; if (pgc_config->flags & MDP_PP_OPS_WRITE) { addr = mixer->base + <API key>; pp_update_argc_lut(addr, pgc_config); } if (pgc_config->flags & MDP_PP_OPS_DISABLE) pp_sts->argc_sts &= ~PP_STS_ENABLE; else if (pgc_config->flags & MDP_PP_OPS_ENABLE) pp_sts->argc_sts |= PP_STS_ENABLE; ctl->flush_bits |= BIT(6) << dspp_num; /* LAYER_MIXER */ } /* update LM opmode if LM needs flush */ if ((pp_sts->argc_sts & PP_STS_ENABLE) && (ctl->flush_bits & (BIT(6) << dspp_num))) { addr = mixer->base + <API key>; opmode = readl_relaxed(addr); opmode |= (1 << 0); /* GC_LUT_EN */ writel_relaxed(opmode, addr); } return 0; } static char __iomem *<API key>(u32 dspp_num) { struct mdss_data_type *mdata; struct mdss_mdp_mixer *mixer; mdata = mdss_mdp_get_mdata(); if (mdata->nmixers_intf <= dspp_num) { pr_err("Invalid dspp_num=%d", dspp_num); return ERR_PTR(-EINVAL); } mixer = mdata->mixer_intf + dspp_num; return mixer->base; } static char __iomem *<API key>(u32 dspp_num) { struct mdss_data_type *mdata; struct mdss_mdp_mixer *mixer; mdata = mdss_mdp_get_mdata(); if (mdata->nmixers_intf <= dspp_num) { pr_err("Invalid dspp_num=%d", dspp_num); return ERR_PTR(-EINVAL); } mixer = mdata->mixer_intf + dspp_num; return mixer->dspp_base; } /* Assumes that function will be called from within clock enabled space*/ static int pp_histogram_setup(u32 *op, u32 block, struct mdss_mdp_mixer *mix) { int ret = -EINVAL; char __iomem *base; u32 op_flags, kick_base, col_state; struct mdss_data_type *mdata; struct mdss_mdp_pipe *pipe; struct pp_hist_col_info *hist_info; unsigned long flag; if (mix && (PP_LOCAT(block) == MDSS_PP_DSPP_CFG)) { /* HIST_EN & AUTO_CLEAR */ op_flags = BIT(16) | BIT(17); hist_info = &mdss_pp_res->dspp_hist[mix->num]; base = <API key>(PP_BLOCK(block)); kick_base = <API key>; } else if (PP_LOCAT(block) == MDSS_PP_SSPP_CFG) { mdata = mdss_mdp_get_mdata(); pipe = mdss_mdp_pipe_get(mdata, BIT(PP_BLOCK(block))); if (IS_ERR_OR_NULL(pipe)) { pr_debug("pipe DNE (%d)", (u32) BIT(PP_BLOCK(block))); ret = -ENODEV; goto error; } /* HIST_EN & AUTO_CLEAR */ op_flags = BIT(8) + BIT(9); hist_info = &pipe->pp_res.hist; base = pipe->base; kick_base = <API key>; mdss_mdp_pipe_unmap(pipe); } else { pr_warn("invalid histogram location (%d)", block); goto error; } if (hist_info->col_en) { *op |= op_flags; mutex_lock(&hist_info->hist_mutex); spin_lock_irqsave(&hist_info->hist_lock, flag); col_state = hist_info->col_state; if (col_state == HIST_IDLE) { /* Kick off collection */ writel_relaxed(1, base + kick_base); hist_info->col_state = HIST_START; } <API key>(&hist_info->hist_lock, flag); mutex_unlock(&hist_info->hist_mutex); } ret = 0; error: return ret; } static void pp_dither_config(char __iomem *addr, struct pp_sts_type *pp_sts, struct mdp_dither_cfg_data *dither_cfg) { u32 data; int i; if (dither_cfg->flags & MDP_PP_OPS_WRITE) { data = dither_depth_map[dither_cfg->g_y_depth]; data |= dither_depth_map[dither_cfg->b_cb_depth] << 2; data |= dither_depth_map[dither_cfg->r_cr_depth] << 4; writel_relaxed(data, addr); addr += 0x14; for (i = 0; i < 16; i += 4) { data = dither_matrix[i] | (dither_matrix[i + 1] << 4) | (dither_matrix[i + 2] << 8) | (dither_matrix[i + 3] << 12); writel_relaxed(data, addr); addr += 4; } } if (dither_cfg->flags & MDP_PP_OPS_DISABLE) pp_sts->dither_sts &= ~PP_STS_ENABLE; else if (dither_cfg->flags & MDP_PP_OPS_ENABLE) pp_sts->dither_sts |= PP_STS_ENABLE; <API key>(&pp_sts->dither_sts, dither_cfg->flags); } static void <API key>(struct mdss_mdp_ctl *ctl, u32 num, struct pp_sts_type *pp_sts, int mdp_rev, u32 *opmode) { int side; side = pp_num_to_side(ctl, num); if (side < 0) return; if (pp_sts_is_enabled(pp_sts->pa_sts, side)) *opmode |= <API key>; /* PA_EN */ if (mdp_rev >= MDSS_MDP_HW_REV_103) { if (pp_sts->pa_sts & PP_STS_PA_HUE_MASK) *opmode |= <API key>; if (pp_sts->pa_sts & PP_STS_PA_SAT_MASK) *opmode |= <API key>; if (pp_sts->pa_sts & PP_STS_PA_VAL_MASK) *opmode |= <API key>; if (pp_sts->pa_sts & PP_STS_PA_CONT_MASK) *opmode |= <API key>; if (pp_sts->pa_sts & <API key>) *opmode |= <API key>; if (pp_sts->pa_sts & <API key>) *opmode |= <API key>; if (pp_sts->pa_sts & <API key>) *opmode |= <API key>; if (pp_sts->pa_sts & <API key>) *opmode |= <API key>; if (pp_sts->pa_sts & <API key>) *opmode |= <API key>; if (pp_sts->pa_sts & <API key>) *opmode |= <API key>; if (pp_sts->pa_sts & <API key>) *opmode |= <API key>; if (pp_sts->pa_sts & <API key>) *opmode |= <API key>; } if (pp_sts_is_enabled(pp_sts->pcc_sts, side)) *opmode |= <API key>; /* PCC_EN */ if (pp_sts_is_enabled(pp_sts->igc_sts, side)) { *opmode |= <API key> | /* IGC_LUT_EN */ (pp_sts->igc_tbl_idx << 1); } if (pp_sts->enhist_sts & PP_STS_ENABLE) { *opmode |= <API key> | /* HIST_LUT_EN */ <API key>; /* PA_EN */ } if (pp_sts_is_enabled(pp_sts->dither_sts, side)) *opmode |= <API key>; /* DITHER_EN */ if (pp_sts_is_enabled(pp_sts->gamut_sts, side)) { *opmode |= <API key>; /* GAMUT_EN */ if (pp_sts->gamut_sts & PP_STS_GAMUT_FIRST) *opmode |= <API key>; } if (pp_sts_is_enabled(pp_sts->pgc_sts, side)) *opmode |= <API key>; } static int pp_dspp_setup(u32 disp_num, struct mdss_mdp_mixer *mixer) { u32 ad_flags, flags, dspp_num, opmode = 0, ad_bypass; struct mdp_pgc_lut_data *pgc_config; struct pp_sts_type *pp_sts; char __iomem *base, *addr; int ret = 0; struct mdss_data_type *mdata; struct mdss_ad_info *ad = NULL; struct mdss_mdp_ad *ad_hw = NULL; struct mdss_mdp_ctl *ctl; u32 mixer_cnt; u32 mixer_id[<API key>]; if (!mixer || !mixer->ctl || !mixer->ctl->mdata) return -EINVAL; ctl = mixer->ctl; mdata = ctl->mdata; dspp_num = mixer->num; /* no corresponding dspp */ if ((mixer->type != <API key>) || (dspp_num >= MDSS_MDP_MAX_DSPP)) return -EINVAL; base = <API key>(dspp_num); mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_ON, false); ret = pp_histogram_setup(&opmode, MDSS_PP_DSPP_CFG | dspp_num, mixer); if (ret) goto dspp_exit; if (disp_num < MDSS_BLOCK_DISP_NUM) flags = mdss_pp_res->pp_disp_flags[disp_num]; else flags = 0; mixer_cnt = <API key>(disp_num, mixer_id); if (dspp_num < mdata->nad_cfgs && disp_num < mdata->nad_cfgs && (mixer_cnt <= mdata-><API key>)) { ad = &mdata->ad_cfgs[disp_num]; ad_flags = ad->reg_sts; ad_hw = &mdata->ad_off[dspp_num]; } else { ad_flags = 0; } /* call calibration specific processing here */ if (ctl->mfd->calib_mode) goto flush_exit; /* nothing to update */ if ((!flags) && (!(opmode)) && (!ad_flags)) goto dspp_exit; pp_sts = &mdss_pp_res->pp_disp_sts[disp_num]; if (mdata->mdp_rev >= MDSS_MDP_HW_REV_103) { pp_pa_v2_config(flags, base + <API key>, pp_sts, &mdss_pp_res->pa_v2_disp_cfg[disp_num], PP_DSPP); } else pp_pa_config(flags, base + <API key>, pp_sts, &mdss_pp_res->pa_disp_cfg[disp_num]); pp_pcc_config(flags, base + <API key>, pp_sts, &mdss_pp_res->pcc_disp_cfg[disp_num]); pp_igc_config(flags, mdata->mdp_base + <API key>, pp_sts, &mdss_pp_res->igc_disp_cfg[disp_num], dspp_num); pp_enhist_config(flags, base + <API key>, pp_sts, &mdss_pp_res->enhist_disp_cfg[disp_num]); if (pp_sts->enhist_sts & PP_STS_ENABLE && !(pp_sts->pa_sts & PP_STS_ENABLE)) { /* Program default value */ addr = base + <API key>; writel_relaxed(0, addr); writel_relaxed(0, addr + 4); writel_relaxed(0, addr + 8); writel_relaxed(0, addr + 12); } if (flags & <API key>) { addr = base + <API key>; pp_dither_config(addr, pp_sts, &mdss_pp_res->dither_disp_cfg[disp_num]); } if (flags & <API key>) pp_gamut_config(&mdss_pp_res->gamut_disp_cfg[disp_num], base, pp_sts); if (flags & PP_FLAGS_DIRTY_PGC) { pgc_config = &mdss_pp_res->pgc_disp_cfg[disp_num]; if (pgc_config->flags & MDP_PP_OPS_WRITE) { addr = base + <API key>; pp_update_argc_lut(addr, pgc_config); } if (pgc_config->flags & MDP_PP_OPS_DISABLE) pp_sts->pgc_sts &= ~PP_STS_ENABLE; else if (pgc_config->flags & MDP_PP_OPS_ENABLE) pp_sts->pgc_sts |= PP_STS_ENABLE; <API key>(&pp_sts->pgc_sts, pgc_config->flags); } <API key>(ctl, dspp_num, pp_sts, mdata->mdp_rev, &opmode); flush_exit: if (ad_hw) { mutex_lock(&ad->lock); ad_flags = ad->reg_sts; if (ad_flags & <API key>) pp_ad_input_write(ad_hw, ad); if (ad_flags & <API key>) pp_ad_init_write(ad_hw, ad, ctl); if (ad_flags & PP_AD_STS_DIRTY_CFG) pp_ad_cfg_write(ad_hw, ad); pp_ad_bypass_config(ad, ctl, ad_hw->num, &ad_bypass); writel_relaxed(ad_bypass, ad_hw->base); mutex_unlock(&ad->lock); } writel_relaxed(opmode, base + <API key>); ctl->flush_bits |= BIT(13 + dspp_num); wmb(); dspp_exit: mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false); return ret; } int mdss_mdp_pp_setup(struct mdss_mdp_ctl *ctl) { int ret = 0; if ((!ctl->mfd) || (!mdss_pp_res)) return -EINVAL; /* TODO: have some sort of reader/writer lock to prevent unclocked * access while display power is toggled */ if (!ctl->mfd->panel_power_on) { ret = -EPERM; goto error; } mutex_lock(&ctl->mfd->lock); ret = <API key>(ctl); mutex_unlock(&ctl->mfd->lock); error: return ret; } /* call only when holding and mfd->lock */ int <API key>(struct mdss_mdp_ctl *ctl) { struct mdss_data_type *mdata = ctl->mdata; int ret = 0; u32 mixer_cnt; u32 mixer_id[<API key>]; u32 disp_num; int i; bool valid_mixers = true; if ((!ctl->mfd) || (!mdss_pp_res)) return -EINVAL; /* treat fb_num the same as block logical id*/ disp_num = ctl->mfd->index; mixer_cnt = <API key>(disp_num, mixer_id); if (!mixer_cnt) { valid_mixers = false; ret = -EINVAL; pr_warn("Configuring post processing without mixers, err = %d", ret); goto exit; } if (mdata->nad_cfgs == 0) valid_mixers = false; for (i = 0; i < mixer_cnt && valid_mixers; i++) { if (mixer_id[i] >= mdata->nad_cfgs) valid_mixers = false; } if (valid_mixers && (mixer_cnt <= mdata-><API key>)) { ret = mdss_mdp_ad_setup(ctl->mfd); if (ret < 0) pr_warn("ad_setup(disp%d) returns %d", disp_num, ret); } mutex_lock(&mdss_pp_mutex); if (ctl->mixer_left) { pp_mixer_setup(disp_num, ctl->mixer_left); pp_dspp_setup(disp_num, ctl->mixer_left); } if (ctl->mixer_right) { pp_mixer_setup(disp_num, ctl->mixer_right); pp_dspp_setup(disp_num, ctl->mixer_right); } /* clear dirty flag */ if (disp_num < MDSS_BLOCK_DISP_NUM) { mdss_pp_res->pp_disp_flags[disp_num] = 0; if (disp_num < mdata->nad_cfgs) mdata->ad_cfgs[disp_num].reg_sts = 0; } mutex_unlock(&mdss_pp_mutex); exit: return ret; } /* * Set dirty and write bits on features that were enabled so they will be * reconfigured */ int mdss_mdp_pp_resume(struct mdss_mdp_ctl *ctl, u32 dspp_num) { u32 flags = 0, disp_num, bl; struct pp_sts_type pp_sts; struct mdss_ad_info *ad; struct mdss_data_type *mdata = ctl->mdata; if (dspp_num >= MDSS_MDP_MAX_DSPP) { pr_warn("invalid dspp_num"); return -EINVAL; } disp_num = ctl->mfd->index; if (dspp_num < mdata->nad_cfgs) { ad = &mdata->ad_cfgs[dspp_num]; if (PP_AD_STATE_CFG & ad->state) pp_ad_cfg_write(&mdata->ad_off[dspp_num], ad); if (PP_AD_STATE_INIT & ad->state) pp_ad_init_write(&mdata->ad_off[dspp_num], ad, ctl); if ((PP_AD_STATE_DATA & ad->state) && (ad->sts & PP_STS_ENABLE)) { bl = ad->bl_mfd->bl_level; ad->last_bl = bl; if (ad->state & PP_AD_STATE_BL_LIN) { bl = ad->bl_lin[bl >> ad->bl_bright_shift]; bl = bl << ad->bl_bright_shift; } ad->bl_data = bl; pp_ad_input_write(&mdata->ad_off[dspp_num], ad); } if ((PP_AD_STATE_VSYNC & ad->state) && ad->calc_itr) ctl->add_vsync_handler(ctl, &ad->handle); } pp_sts = mdss_pp_res->pp_disp_sts[disp_num]; if (pp_sts.pa_sts & PP_STS_ENABLE) { flags |= PP_FLAGS_DIRTY_PA; if (mdata->mdp_rev >= MDSS_MDP_HW_REV_103) { if (!(mdss_pp_res->pa_v2_disp_cfg[disp_num].flags & MDP_PP_OPS_DISABLE)) mdss_pp_res->pa_v2_disp_cfg[disp_num].flags |= MDP_PP_OPS_WRITE; } else { if (!(mdss_pp_res->pa_disp_cfg[disp_num].flags & MDP_PP_OPS_DISABLE)) mdss_pp_res->pa_disp_cfg[disp_num].flags |= MDP_PP_OPS_WRITE; } } if (pp_sts.pcc_sts & PP_STS_ENABLE) { flags |= PP_FLAGS_DIRTY_PCC; if (!(mdss_pp_res->pcc_disp_cfg[disp_num].ops & MDP_PP_OPS_DISABLE)) mdss_pp_res->pcc_disp_cfg[disp_num].ops |= MDP_PP_OPS_WRITE; } if (pp_sts.igc_sts & PP_STS_ENABLE) { flags |= PP_FLAGS_DIRTY_IGC; if (!(mdss_pp_res->igc_disp_cfg[disp_num].ops & MDP_PP_OPS_DISABLE)) mdss_pp_res->igc_disp_cfg[disp_num].ops |= MDP_PP_OPS_WRITE; } if (pp_sts.argc_sts & PP_STS_ENABLE) { flags |= PP_FLAGS_DIRTY_ARGC; if (!(mdss_pp_res->argc_disp_cfg[disp_num].flags & MDP_PP_OPS_DISABLE)) mdss_pp_res->argc_disp_cfg[disp_num].flags |= MDP_PP_OPS_WRITE; } if (pp_sts.enhist_sts & PP_STS_ENABLE) { flags |= <API key>; if (!(mdss_pp_res->enhist_disp_cfg[disp_num].ops & MDP_PP_OPS_DISABLE)) mdss_pp_res->enhist_disp_cfg[disp_num].ops |= MDP_PP_OPS_WRITE; } if (pp_sts.dither_sts & PP_STS_ENABLE) { flags |= <API key>; if (!(mdss_pp_res->dither_disp_cfg[disp_num].flags & MDP_PP_OPS_DISABLE)) mdss_pp_res->dither_disp_cfg[disp_num].flags |= MDP_PP_OPS_WRITE; } if (pp_sts.gamut_sts & PP_STS_ENABLE) { flags |= <API key>; if (!(mdss_pp_res->gamut_disp_cfg[disp_num].flags & MDP_PP_OPS_DISABLE)) mdss_pp_res->gamut_disp_cfg[disp_num].flags |= MDP_PP_OPS_WRITE; } if (!disp_num) pp_sts.pgc_sts |= PP_STS_ENABLE; if (pp_sts.pgc_sts & PP_STS_ENABLE) { flags |= PP_FLAGS_DIRTY_PGC; if (!(mdss_pp_res->pgc_disp_cfg[disp_num].flags & MDP_PP_OPS_DISABLE)) mdss_pp_res->pgc_disp_cfg[disp_num].flags |= MDP_PP_OPS_WRITE; } mdss_pp_res->pp_disp_flags[disp_num] |= flags; return 0; } void <API key>(bool enable) { u32 disp_num = 0, copyback = 0; struct mdp_pgc_lut_data *pgc_config; pgc_config = &mdss_pp_res->pgc_disp_cfg[disp_num]; pgc_config->block = <API key>; if (enable) { pgc_config->flags = MDP_PP_OPS_WRITE | MDP_PP_OPS_ENABLE; pgc_config->r_data = &mdss_pp_res->gc_lut_r[disp_num][0]; pgc_config->g_data = &mdss_pp_res->gc_lut_g[disp_num][0]; pgc_config->b_data = &mdss_pp_res->gc_lut_b[disp_num][0]; } else pgc_config->flags = MDP_PP_OPS_WRITE | MDP_PP_OPS_DISABLE; <API key>(pgc_config, &copyback); } void <API key>(int kr, int kg, int kb) { int i; u32 disp_num = 0, copyback = 0; struct mdp_pgc_lut_data *pgc_config; pgc_config = &mdss_pp_res->pgc_disp_cfg[disp_num]; for (i = 0; i < GC_LUT_SEGMENTS; i++) { pgc_config->r_data[i].slope = kr; pgc_config->g_data[i].slope = kg; pgc_config->b_data[i].slope = kb; } <API key>(pgc_config, &copyback); } void mdss_mdp_pp_kcal_pa(struct kcal_lut_data *lut_data) { u32 copyback = 0; struct mdp_pa_cfg_data pa_config; memset(&pa_config, 0, sizeof(struct mdp_pa_cfg_data)); pa_config.block = <API key>; pa_config.pa_data.flags = MDP_PP_OPS_WRITE | MDP_PP_OPS_ENABLE; pa_config.pa_data.sat_adj = lut_data->sat; pa_config.pa_data.hue_adj = lut_data->hue; pa_config.pa_data.val_adj = lut_data->val; pa_config.pa_data.cont_adj = lut_data->cont; mdss_mdp_pa_config(&pa_config, &copyback); } int mdss_mdp_pp_init(struct device *dev) { int i, ret = 0; struct mdss_data_type *mdata = mdss_mdp_get_mdata(); struct mdss_mdp_pipe *vig; struct msm_bus_scale_pdata *pp_bus_pdata; mutex_lock(&mdss_pp_mutex); if (!mdss_pp_res) { mdss_pp_res = devm_kzalloc(dev, sizeof(*mdss_pp_res), GFP_KERNEL); if (mdss_pp_res == NULL) { pr_err("%s mdss_pp_res allocation failed!", __func__); ret = -ENOMEM; } else { for (i = 0; i < MDSS_MDP_MAX_DSPP; i++) { mutex_init( &mdss_pp_res->dspp_hist[i].hist_mutex); spin_lock_init( &mdss_pp_res->dspp_hist[i].hist_lock); } } } if (mdata) { vig = mdata->vig_pipes; for (i = 0; i < mdata->nvig_pipes; i++) { mutex_init(&vig[i].pp_res.hist.hist_mutex); spin_lock_init(&vig[i].pp_res.hist.hist_lock); } if (!mdata->pp_bus_hdl) { pp_bus_pdata = &<API key>; for (i = 0; i < pp_bus_pdata->num_usecases; i++) { mdp_pp_bus_usecases[i].num_paths = 1; mdp_pp_bus_usecases[i].vectors = &mdp_pp_bus_vectors[i]; } mdata->pp_bus_hdl = <API key>(pp_bus_pdata); if (!mdata->pp_bus_hdl) { pr_err("not able to register pp_bus_scale\n"); ret = -ENOMEM; } pr_debug("register pp_bus_hdl=%x\n", mdata->pp_bus_hdl); } } mutex_unlock(&mdss_pp_mutex); return ret; } void mdss_mdp_pp_term(struct device *dev) { struct mdss_data_type *mdata = mdss_mdp_get_mdata(); if (mdata->pp_bus_hdl) { <API key>(mdata->pp_bus_hdl); mdata->pp_bus_hdl = 0; } if (!mdss_pp_res) { mutex_lock(&mdss_pp_mutex); devm_kfree(dev, mdss_pp_res); mdss_pp_res = NULL; mutex_unlock(&mdss_pp_mutex); } } static int pp_get_dspp_num(u32 disp_num, u32 *dspp_num) { int i; u32 mixer_cnt; u32 mixer_id[<API key>]; mixer_cnt = <API key>(disp_num, mixer_id); if (!mixer_cnt) return -EPERM; /* only read the first mixer */ for (i = 0; i < mixer_cnt; i++) { if (mixer_id[i] < MDSS_MDP_MAX_DSPP) break; } if (i >= mixer_cnt) return -EPERM; *dspp_num = mixer_id[i]; return 0; } int mdss_mdp_pa_config(struct mdp_pa_cfg_data *config, u32 *copyback) { int ret = 0; u32 disp_num, dspp_num = 0; struct mdss_data_type *mdata = mdss_mdp_get_mdata(); char __iomem *pa_addr; if (mdata->mdp_rev >= MDSS_MDP_HW_REV_103) return -EINVAL; if ((config->block < <API key>) || (config->block >= MDP_BLOCK_MAX)) return -EINVAL; mutex_lock(&mdss_pp_mutex); disp_num = config->block - <API key>; if (config->pa_data.flags & MDP_PP_OPS_READ) { ret = pp_get_dspp_num(disp_num, &dspp_num); if (ret) { pr_err("no dspp connects to disp %d", disp_num); goto pa_config_exit; } mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_ON, false); pa_addr = <API key>(dspp_num) + <API key>; config->pa_data.hue_adj = readl_relaxed(pa_addr); pa_addr += 4; config->pa_data.sat_adj = readl_relaxed(pa_addr); pa_addr += 4; config->pa_data.val_adj = readl_relaxed(pa_addr); pa_addr += 4; config->pa_data.cont_adj = readl_relaxed(pa_addr); *copyback = 1; mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false); } else { mdss_pp_res->pa_disp_cfg[disp_num] = config->pa_data; mdss_pp_res->pp_disp_flags[disp_num] |= PP_FLAGS_DIRTY_PA; } pa_config_exit: mutex_unlock(&mdss_pp_mutex); return ret; } int <API key>(struct mdp_pa_v2_cfg_data *config, u32 *copyback) { int ret = 0; u32 disp_num, dspp_num = 0; char __iomem *pa_addr; struct mdss_data_type *mdata = mdss_mdp_get_mdata(); if (mdata->mdp_rev < MDSS_MDP_HW_REV_103) return -EINVAL; if ((config->block < <API key>) || (config->block >= MDP_BLOCK_MAX)) return -EINVAL; if ((config->pa_v2_data.flags & MDSS_PP_SPLIT_MASK) == MDSS_PP_SPLIT_MASK) { pr_warn("Can't set both split bits\n"); return -EINVAL; } mutex_lock(&mdss_pp_mutex); disp_num = config->block - <API key>; if (config->pa_v2_data.flags & MDP_PP_OPS_READ) { ret = pp_get_dspp_num(disp_num, &dspp_num); if (ret) { pr_err("no dspp connects to disp %d", disp_num); goto pa_config_exit; } mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_ON, false); pa_addr = <API key>(dspp_num); if (IS_ERR(pa_addr)) { ret = PTR_ERR(pa_addr); goto pa_config_exit; } else pa_addr += <API key>; ret = pp_read_pa_v2_regs(pa_addr, &config->pa_v2_data, disp_num); if (ret) goto pa_config_exit; *copyback = 1; mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false); } else { if (config->pa_v2_data.flags & <API key>) { ret = <API key>(config, disp_num); if (ret) goto pa_config_exit; } mdss_pp_res->pa_v2_disp_cfg[disp_num] = config->pa_v2_data; mdss_pp_res->pa_v2_disp_cfg[disp_num].six_zone_curve_p0 = &mdss_pp_res-><API key>[disp_num][0]; mdss_pp_res->pa_v2_disp_cfg[disp_num].six_zone_curve_p1 = &mdss_pp_res-><API key>[disp_num][0]; mdss_pp_res->pp_disp_flags[disp_num] |= PP_FLAGS_DIRTY_PA; } pa_config_exit: mutex_unlock(&mdss_pp_mutex); return ret; } static int pp_read_pa_v2_regs(char __iomem *addr, struct mdp_pa_v2_data *pa_v2_config, u32 disp_num) { int i; u32 data; if (pa_v2_config->flags & <API key>) pa_v2_config->global_hue_adj = readl_relaxed(addr); addr += 4; if (pa_v2_config->flags & <API key>) pa_v2_config->global_sat_adj = readl_relaxed(addr); addr += 4; if (pa_v2_config->flags & <API key>) pa_v2_config->global_val_adj = readl_relaxed(addr); addr += 4; if (pa_v2_config->flags & <API key>) pa_v2_config->global_cont_adj = readl_relaxed(addr); addr += 4; /* Six zone LUT and thresh data */ if (pa_v2_config->flags & <API key>) { if (pa_v2_config->six_zone_len != <API key>) return -EINVAL; data = (3 << 25); writel_relaxed(data, addr); for (i = 0; i < <API key>; i++) { addr += 4; mdss_pp_res-><API key>[disp_num][i] = readl_relaxed(addr); addr -= 4; mdss_pp_res-><API key>[disp_num][i] = readl_relaxed(addr) & 0xFFF; } if (copy_to_user(pa_v2_config->six_zone_curve_p0, &mdss_pp_res-><API key>[disp_num][0], pa_v2_config->six_zone_len * sizeof(u32))) { return -EFAULT; } if (copy_to_user(pa_v2_config->six_zone_curve_p1, &mdss_pp_res-><API key>[disp_num][0], pa_v2_config->six_zone_len * sizeof(u32))) { return -EFAULT; } addr += 8; pa_v2_config->six_zone_thresh = readl_relaxed(addr); addr += 4; } else { addr += 12; } /* Skin memory color config registers */ if (pa_v2_config->flags & <API key>) <API key>(addr, &pa_v2_config->skin_cfg); addr += 0x14; /* Sky memory color config registers */ if (pa_v2_config->flags & <API key>) <API key>(addr, &pa_v2_config->sky_cfg); addr += 0x14; /* Foliage memory color config registers */ if (pa_v2_config->flags & <API key>) <API key>(addr, &pa_v2_config->fol_cfg); return 0; } static void <API key>(char __iomem *addr, struct mdp_pa_mem_col_cfg *mem_col_cfg) { mem_col_cfg->color_adjust_p0 = readl_relaxed(addr); addr += 4; mem_col_cfg->color_adjust_p1 = readl_relaxed(addr); addr += 4; mem_col_cfg->hue_region = readl_relaxed(addr); addr += 4; mem_col_cfg->sat_region = readl_relaxed(addr); addr += 4; mem_col_cfg->val_region = readl_relaxed(addr); } static int <API key>(struct mdp_pa_v2_cfg_data *pa_v2_config, u32 disp_num) { if (pa_v2_config->pa_v2_data.six_zone_len != <API key>) return -EINVAL; if (copy_from_user(&mdss_pp_res-><API key>[disp_num][0], pa_v2_config->pa_v2_data.six_zone_curve_p0, pa_v2_config->pa_v2_data.six_zone_len * sizeof(u32))) { return -EFAULT; } if (copy_from_user(&mdss_pp_res-><API key>[disp_num][0], pa_v2_config->pa_v2_data.six_zone_curve_p1, pa_v2_config->pa_v2_data.six_zone_len * sizeof(u32))) { return -EFAULT; } return 0; } static void pp_read_pcc_regs(char __iomem *addr, struct mdp_pcc_cfg_data *cfg_ptr) { cfg_ptr->r.c = readl_relaxed(addr); cfg_ptr->g.c = readl_relaxed(addr + 4); cfg_ptr->b.c = readl_relaxed(addr + 8); addr += 0x10; cfg_ptr->r.r = readl_relaxed(addr); cfg_ptr->g.r = readl_relaxed(addr + 4); cfg_ptr->b.r = readl_relaxed(addr + 8); addr += 0x10; cfg_ptr->r.g = readl_relaxed(addr); cfg_ptr->g.g = readl_relaxed(addr + 4); cfg_ptr->b.g = readl_relaxed(addr + 8); addr += 0x10; cfg_ptr->r.b = readl_relaxed(addr); cfg_ptr->g.b = readl_relaxed(addr + 4); cfg_ptr->b.b = readl_relaxed(addr + 8); addr += 0x10; cfg_ptr->r.rr = readl_relaxed(addr); cfg_ptr->g.rr = readl_relaxed(addr + 4); cfg_ptr->b.rr = readl_relaxed(addr + 8); addr += 0x10; cfg_ptr->r.rg = readl_relaxed(addr); cfg_ptr->g.rg = readl_relaxed(addr + 4); cfg_ptr->b.rg = readl_relaxed(addr + 8); addr += 0x10; cfg_ptr->r.rb = readl_relaxed(addr); cfg_ptr->g.rb = readl_relaxed(addr + 4); cfg_ptr->b.rb = readl_relaxed(addr + 8); addr += 0x10; cfg_ptr->r.gg = readl_relaxed(addr); cfg_ptr->g.gg = readl_relaxed(addr + 4); cfg_ptr->b.gg = readl_relaxed(addr + 8); addr += 0x10; cfg_ptr->r.gb = readl_relaxed(addr); cfg_ptr->g.gb = readl_relaxed(addr + 4); cfg_ptr->b.gb = readl_relaxed(addr + 8); addr += 0x10; cfg_ptr->r.bb = readl_relaxed(addr); cfg_ptr->g.bb = readl_relaxed(addr + 4); cfg_ptr->b.bb = readl_relaxed(addr + 8); addr += 0x10; cfg_ptr->r.rgb_0 = readl_relaxed(addr); cfg_ptr->g.rgb_0 = readl_relaxed(addr + 4); cfg_ptr->b.rgb_0 = readl_relaxed(addr + 8); addr += 0x10; cfg_ptr->r.rgb_1 = readl_relaxed(addr); cfg_ptr->g.rgb_1 = readl_relaxed(addr + 4); cfg_ptr->b.rgb_1 = readl_relaxed(addr + 8); } static void pp_update_pcc_regs(char __iomem *addr, struct mdp_pcc_cfg_data *cfg_ptr) { writel_relaxed(cfg_ptr->r.c, addr); writel_relaxed(cfg_ptr->g.c, addr + 4); writel_relaxed(cfg_ptr->b.c, addr + 8); addr += 0x10; writel_relaxed(cfg_ptr->r.r, addr); writel_relaxed(cfg_ptr->g.r, addr + 4); writel_relaxed(cfg_ptr->b.r, addr + 8); addr += 0x10; writel_relaxed(cfg_ptr->r.g, addr); writel_relaxed(cfg_ptr->g.g, addr + 4); writel_relaxed(cfg_ptr->b.g, addr + 8); addr += 0x10; writel_relaxed(cfg_ptr->r.b, addr); writel_relaxed(cfg_ptr->g.b, addr + 4); writel_relaxed(cfg_ptr->b.b, addr + 8); addr += 0x10; writel_relaxed(cfg_ptr->r.rr, addr); writel_relaxed(cfg_ptr->g.rr, addr + 4); writel_relaxed(cfg_ptr->b.rr, addr + 8); addr += 0x10; writel_relaxed(cfg_ptr->r.rg, addr); writel_relaxed(cfg_ptr->g.rg, addr + 4); writel_relaxed(cfg_ptr->b.rg, addr + 8); addr += 0x10; writel_relaxed(cfg_ptr->r.rb, addr); writel_relaxed(cfg_ptr->g.rb, addr + 4); writel_relaxed(cfg_ptr->b.rb, addr + 8); addr += 0x10; writel_relaxed(cfg_ptr->r.gg, addr); writel_relaxed(cfg_ptr->g.gg, addr + 4); writel_relaxed(cfg_ptr->b.gg, addr + 8); addr += 0x10; writel_relaxed(cfg_ptr->r.gb, addr); writel_relaxed(cfg_ptr->g.gb, addr + 4); writel_relaxed(cfg_ptr->b.gb, addr + 8); addr += 0x10; writel_relaxed(cfg_ptr->r.bb, addr); writel_relaxed(cfg_ptr->g.bb, addr + 4); writel_relaxed(cfg_ptr->b.bb, addr + 8); addr += 0x10; writel_relaxed(cfg_ptr->r.rgb_0, addr); writel_relaxed(cfg_ptr->g.rgb_0, addr + 4); writel_relaxed(cfg_ptr->b.rgb_0, addr + 8); addr += 0x10; writel_relaxed(cfg_ptr->r.rgb_1, addr); writel_relaxed(cfg_ptr->g.rgb_1, addr + 4); writel_relaxed(cfg_ptr->b.rgb_1, addr + 8); } int mdss_mdp_pcc_config(struct mdp_pcc_cfg_data *config, u32 *copyback) { int ret = 0; u32 disp_num, dspp_num = 0; char __iomem *addr; if ((config->block < <API key>) || (config->block >= MDP_BLOCK_MAX)) return -EINVAL; if ((config->ops & MDSS_PP_SPLIT_MASK) == MDSS_PP_SPLIT_MASK) { pr_warn("Can't set both split bits\n"); return -EINVAL; } mutex_lock(&mdss_pp_mutex); disp_num = config->block - <API key>; if (config->ops & MDP_PP_OPS_READ) { ret = pp_get_dspp_num(disp_num, &dspp_num); if (ret) { pr_err("%s, no dspp connects to disp %d", __func__, disp_num); goto pcc_config_exit; } mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_ON, false); addr = <API key>(dspp_num) + <API key>; pp_read_pcc_regs(addr, config); *copyback = 1; mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false); } else { mdss_pp_res->pcc_disp_cfg[disp_num] = *config; mdss_pp_res->pp_disp_flags[disp_num] |= PP_FLAGS_DIRTY_PCC; } pcc_config_exit: mutex_unlock(&mdss_pp_mutex); return ret; } #ifdef CONFIG_MACH_LGE int <API key>(u32 enable) { int i; int disp_num = 0; struct mdss_mdp_ctl *ctl; struct mdss_mdp_ctl *ctl_d = NULL; struct mdss_data_type *mdata; struct mdp_igc_lut_data *igc_data; mdata = mdss_mdp_get_mdata(); for (i = 0; i < mdata->nctl; i++) { ctl = mdata->ctl_off + i; if ((ctl->power_on) && (ctl->mfd) && (ctl->mfd->index == 0)) { ctl_d = ctl; break; } } igc_data = &mdss_pp_res->igc_disp_cfg[disp_num]; igc_data->c0_c1_data = &mdss_pp_res->igc_lut_c0c1[disp_num][0]; igc_data->c2_data = &mdss_pp_res->igc_lut_c2[disp_num][0]; igc_data->block = <API key>; igc_data->len = 256; if (ctl_d && enable) { igc_data->ops = MDP_PP_OPS_WRITE | MDP_PP_OPS_ENABLE; for (i = 0; i < 256 ; i++) { igc_c0_c1[i] = (igc_Table_RGB[i]&0xFFF)|((igc_Table_RGB[i]&0xFFF))<<16; igc_c2[i] = igc_Table_RGB[i]; } igc_data->c0_c1_data = &igc_c0_c1[0]; igc_data->c2_data = &igc_c2[0]; } else if (ctl_d && !enable) { igc_data->ops = MDP_PP_OPS_WRITE | MDP_PP_OPS_DISABLE; } else { pr_info("!!!!!!!!!!!!!!!!! null !!!!!!!!!!!!\n"); } mdss_pp_res->pp_disp_flags[disp_num] |= PP_FLAGS_DIRTY_IGC; return 0; } #endif static void pp_read_igc_lut(struct mdp_igc_lut_data *cfg, char __iomem *addr, u32 blk_idx) { int i; u32 data; /* INDEX_UPDATE & VALUE_UPDATEN */ data = (3 << 24) | (((~(1 << blk_idx)) & 0x7) << 28); writel_relaxed(data, addr); for (i = 0; i < cfg->len; i++) cfg->c0_c1_data[i] = readl_relaxed(addr) & 0xFFF; addr += 0x4; writel_relaxed(data, addr); for (i = 0; i < cfg->len; i++) cfg->c0_c1_data[i] |= (readl_relaxed(addr) & 0xFFF) << 16; addr += 0x4; writel_relaxed(data, addr); for (i = 0; i < cfg->len; i++) cfg->c2_data[i] = readl_relaxed(addr) & 0xFFF; } static void pp_update_igc_lut(struct mdp_igc_lut_data *cfg, char __iomem *addr, u32 blk_idx) { int i; u32 data; /* INDEX_UPDATE */ data = (1 << 25) | (((~(1 << blk_idx)) & 0x7) << 28); writel_relaxed((cfg->c0_c1_data[0] & 0xFFF) | data, addr); /* disable index update */ data &= ~(1 << 25); for (i = 1; i < cfg->len; i++) writel_relaxed((cfg->c0_c1_data[i] & 0xFFF) | data, addr); addr += 0x4; data |= (1 << 25); writel_relaxed(((cfg->c0_c1_data[0] >> 16) & 0xFFF) | data, addr); data &= ~(1 << 25); for (i = 1; i < cfg->len; i++) writel_relaxed(((cfg->c0_c1_data[i] >> 16) & 0xFFF) | data, addr); addr += 0x4; data |= (1 << 25); writel_relaxed((cfg->c2_data[0] & 0xFFF) | data, addr); data &= ~(1 << 25); for (i = 1; i < cfg->len; i++) writel_relaxed((cfg->c2_data[i] & 0xFFF) | data, addr); } int <API key>(struct mdss_mdp_ctl *ctl) { int ret = 0; u32 copyback = 0; u32 copy_from_kernel = 1; struct mdp_igc_lut_data config; if (!ctl) return -EINVAL; config.len = IGC_LUT_ENTRIES; config.ops = MDP_PP_OPS_WRITE | MDP_PP_OPS_ENABLE; config.block = (ctl->mfd->index) + <API key>; config.c0_c1_data = igc_limited; config.c2_data = igc_limited; ret = <API key>(&config, &copyback, copy_from_kernel); return ret; } int <API key>(struct mdp_igc_lut_data *config, u32 *copyback, u32 copy_from_kernel) { int ret = 0; u32 tbl_idx, disp_num, dspp_num = 0; struct mdp_igc_lut_data local_cfg; char __iomem *igc_addr; struct mdss_data_type *mdata = mdss_mdp_get_mdata(); if ((config->block < <API key>) || (config->block >= MDP_BLOCK_MAX)) return -EINVAL; if (config->len != IGC_LUT_ENTRIES) return -EINVAL; if ((config->ops & MDSS_PP_SPLIT_MASK) == MDSS_PP_SPLIT_MASK) { pr_warn("Can't set both split bits\n"); return -EINVAL; } mutex_lock(&mdss_pp_mutex); disp_num = config->block - <API key>; if (config->ops & MDP_PP_OPS_READ) { ret = pp_get_dspp_num(disp_num, &dspp_num); if (ret) { pr_err("%s, no dspp connects to disp %d", __func__, disp_num); goto igc_config_exit; } mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_ON, false); if (config->ops & <API key>) tbl_idx = 1; else if (config->ops & <API key>) tbl_idx = 2; else tbl_idx = 0; igc_addr = mdata->mdp_base + <API key> + (0x10 * tbl_idx); local_cfg = *config; local_cfg.c0_c1_data = &mdss_pp_res->igc_lut_c0c1[disp_num][0]; local_cfg.c2_data = &mdss_pp_res->igc_lut_c2[disp_num][0]; pp_read_igc_lut(&local_cfg, igc_addr, dspp_num); if (copy_to_user(config->c0_c1_data, local_cfg.c2_data, config->len * sizeof(u32))) { ret = -EFAULT; mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false); goto igc_config_exit; } if (copy_to_user(config->c2_data, local_cfg.c0_c1_data, config->len * sizeof(u32))) { ret = -EFAULT; mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false); goto igc_config_exit; } *copyback = 1; mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false); } else { if (copy_from_kernel) { memcpy(&mdss_pp_res->igc_lut_c0c1[disp_num][0], config->c0_c1_data, config->len * sizeof(u32)); memcpy(&mdss_pp_res->igc_lut_c2[disp_num][0], config->c2_data, config->len * sizeof(u32)); } else { if (copy_from_user( &mdss_pp_res->igc_lut_c0c1[disp_num][0], config->c0_c1_data, config->len * sizeof(u32))) { ret = -EFAULT; goto igc_config_exit; } if (copy_from_user( &mdss_pp_res->igc_lut_c2[disp_num][0], config->c2_data, config->len * sizeof(u32))) { ret = -EFAULT; goto igc_config_exit; } } mdss_pp_res->igc_disp_cfg[disp_num] = *config; mdss_pp_res->igc_disp_cfg[disp_num].c0_c1_data = &mdss_pp_res->igc_lut_c0c1[disp_num][0]; mdss_pp_res->igc_disp_cfg[disp_num].c2_data = &mdss_pp_res->igc_lut_c2[disp_num][0]; mdss_pp_res->pp_disp_flags[disp_num] |= PP_FLAGS_DIRTY_IGC; } igc_config_exit: mutex_unlock(&mdss_pp_mutex); return ret; } static void <API key>(char __iomem *addr, struct mdp_ar_gc_lut_data *lut_data, uint8_t num_stages) { int i, start_idx, idx; start_idx = ((readl_relaxed(addr) >> 16) & 0xF) + 1; for (i = start_idx; i < GC_LUT_SEGMENTS; i++) { idx = min((uint8_t)i, (uint8_t)(num_stages-1)); writel_relaxed(lut_data[idx].x_start, addr); } for (i = 0; i < start_idx; i++) { idx = min((uint8_t)i, (uint8_t)(num_stages-1)); writel_relaxed(lut_data[idx].x_start, addr); } addr += 4; start_idx = ((readl_relaxed(addr) >> 16) & 0xF) + 1; for (i = start_idx; i < GC_LUT_SEGMENTS; i++) { idx = min((uint8_t)i, (uint8_t)(num_stages-1)); writel_relaxed(lut_data[idx].slope, addr); } for (i = 0; i < start_idx; i++) { idx = min((uint8_t)i, (uint8_t)(num_stages-1)); writel_relaxed(lut_data[idx].slope, addr); } addr += 4; start_idx = ((readl_relaxed(addr) >> 16) & 0xF) + 1; for (i = start_idx; i < GC_LUT_SEGMENTS; i++) { idx = min((uint8_t)i, (uint8_t)(num_stages-1)); writel_relaxed(lut_data[idx].offset, addr); } for (i = 0; i < start_idx; i++) { idx = min((uint8_t)i, (uint8_t)(num_stages-1)); writel_relaxed(lut_data[idx].offset, addr); } } static void pp_update_argc_lut(char __iomem *addr, struct mdp_pgc_lut_data *config) { <API key>(addr, config->r_data, config->num_r_stages); addr += 0x10; <API key>(addr, config->g_data, config->num_g_stages); addr += 0x10; <API key>(addr, config->b_data, config->num_b_stages); } static void pp_read_gc_one_lut(char __iomem *addr, struct mdp_ar_gc_lut_data *gc_data) { int i, start_idx, data; data = readl_relaxed(addr); start_idx = (data >> 16) & 0xF; gc_data[start_idx].x_start = data & 0xFFF; for (i = start_idx + 1; i < GC_LUT_SEGMENTS; i++) { data = readl_relaxed(addr); gc_data[i].x_start = data & 0xFFF; } for (i = 0; i < start_idx; i++) { data = readl_relaxed(addr); gc_data[i].x_start = data & 0xFFF; } addr += 4; data = readl_relaxed(addr); start_idx = (data >> 16) & 0xF; gc_data[start_idx].slope = data & 0x7FFF; for (i = start_idx + 1; i < GC_LUT_SEGMENTS; i++) { data = readl_relaxed(addr); gc_data[i].slope = data & 0x7FFF; } for (i = 0; i < start_idx; i++) { data = readl_relaxed(addr); gc_data[i].slope = data & 0x7FFF; } addr += 4; data = readl_relaxed(addr); start_idx = (data >> 16) & 0xF; gc_data[start_idx].offset = data & 0x7FFF; for (i = start_idx + 1; i < GC_LUT_SEGMENTS; i++) { data = readl_relaxed(addr); gc_data[i].offset = data & 0x7FFF; } for (i = 0; i < start_idx; i++) { data = readl_relaxed(addr); gc_data[i].offset = data & 0x7FFF; } } static int pp_read_argc_lut(struct mdp_pgc_lut_data *config, char __iomem *addr) { int ret = 0; pp_read_gc_one_lut(addr, config->r_data); addr += 0x10; pp_read_gc_one_lut(addr, config->g_data); addr += 0x10; pp_read_gc_one_lut(addr, config->b_data); return ret; } /* Note: Assumes that its inputs have been checked by calling function */ static void pp_update_hist_lut(char __iomem *addr, struct mdp_hist_lut_data *cfg) { int i; for (i = 0; i < ENHIST_LUT_ENTRIES; i++) writel_relaxed(cfg->data[i], addr); /* swap */ if (PP_LOCAT(cfg->block) == MDSS_PP_DSPP_CFG) writel_relaxed(1, addr + 4); else writel_relaxed(1, addr + 16); } int <API key>(struct mdp_pgc_lut_data *config, u32 *copyback) { int ret = 0; u32 disp_num, dspp_num = 0; char __iomem *argc_addr = 0; if ((PP_BLOCK(config->block) < <API key>) || (PP_BLOCK(config->block) >= MDP_BLOCK_MAX)) return -EINVAL; if ((config->flags & MDSS_PP_SPLIT_MASK) == MDSS_PP_SPLIT_MASK) { pr_warn("Can't set both split bits\n"); return -EINVAL; } mutex_lock(&mdss_pp_mutex); disp_num = PP_BLOCK(config->block) - <API key>; if (config->flags & MDP_PP_OPS_READ) { ret = pp_get_dspp_num(disp_num, &dspp_num); if (ret) { pr_err("%s, no dspp connects to disp %d", __func__, disp_num); goto argc_config_exit; } mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_ON, false); switch (PP_LOCAT(config->block)) { case MDSS_PP_LM_CFG: argc_addr = <API key>(dspp_num) + <API key>; break; case MDSS_PP_DSPP_CFG: argc_addr = <API key>(dspp_num) + <API key>; break; default: mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false); goto argc_config_exit; break; } pp_read_argc_lut(config, argc_addr); *copyback = 1; mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false); } else { switch (PP_LOCAT(config->block)) { case MDSS_PP_LM_CFG: mdss_pp_res->argc_disp_cfg[disp_num] = *config; mdss_pp_res->pp_disp_flags[disp_num] |= PP_FLAGS_DIRTY_ARGC; break; case MDSS_PP_DSPP_CFG: mdss_pp_res->pgc_disp_cfg[disp_num] = *config; mdss_pp_res->pp_disp_flags[disp_num] |= PP_FLAGS_DIRTY_PGC; break; default: break; } } argc_config_exit: mutex_unlock(&mdss_pp_mutex); return ret; } int <API key>(struct mdp_hist_lut_data *config, u32 *copyback) { int i, ret = 0; u32 disp_num, dspp_num = 0; char __iomem *hist_addr; if ((PP_BLOCK(config->block) < <API key>) || (PP_BLOCK(config->block) >= MDP_BLOCK_MAX)) return -EINVAL; mutex_lock(&mdss_pp_mutex); disp_num = PP_BLOCK(config->block) - <API key>; if (config->ops & MDP_PP_OPS_READ) { ret = pp_get_dspp_num(disp_num, &dspp_num); if (ret) { pr_err("%s, no dspp connects to disp %d", __func__, disp_num); goto enhist_config_exit; } mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_ON, false); hist_addr = <API key>(dspp_num) + <API key>; for (i = 0; i < ENHIST_LUT_ENTRIES; i++) mdss_pp_res->enhist_lut[disp_num][i] = readl_relaxed(hist_addr); if (copy_to_user(config->data, &mdss_pp_res->enhist_lut[disp_num][0], ENHIST_LUT_ENTRIES * sizeof(u32))) { mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false); ret = -EFAULT; goto enhist_config_exit; } *copyback = 1; mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false); } else { if (copy_from_user(&mdss_pp_res->enhist_lut[disp_num][0], config->data, ENHIST_LUT_ENTRIES * sizeof(u32))) { ret = -EFAULT; goto enhist_config_exit; } mdss_pp_res->enhist_disp_cfg[disp_num] = *config; mdss_pp_res->enhist_disp_cfg[disp_num].data = &mdss_pp_res->enhist_lut[disp_num][0]; mdss_pp_res->pp_disp_flags[disp_num] |= <API key>; } enhist_config_exit: mutex_unlock(&mdss_pp_mutex); return ret; } int <API key>(struct mdp_dither_cfg_data *config, u32 *copyback) { u32 disp_num; if ((config->block < <API key>) || (config->block >= MDP_BLOCK_MAX)) return -EINVAL; if (config->flags & MDP_PP_OPS_READ) return -ENOTSUPP; if ((config->flags & MDSS_PP_SPLIT_MASK) == MDSS_PP_SPLIT_MASK) { pr_warn("Can't set both split bits\n"); return -EINVAL; } mutex_lock(&mdss_pp_mutex); disp_num = config->block - <API key>; mdss_pp_res->dither_disp_cfg[disp_num] = *config; mdss_pp_res->pp_disp_flags[disp_num] |= <API key>; mutex_unlock(&mdss_pp_mutex); return 0; } static int <API key>(struct mdp_gamut_cfg_data *config) { if (config->tbl_size[0] != GAMUT_T0_SIZE) return -EINVAL; if (config->tbl_size[1] != GAMUT_T1_SIZE) return -EINVAL; if (config->tbl_size[2] != GAMUT_T2_SIZE) return -EINVAL; if (config->tbl_size[3] != GAMUT_T3_SIZE) return -EINVAL; if (config->tbl_size[4] != GAMUT_T4_SIZE) return -EINVAL; if (config->tbl_size[5] != GAMUT_T5_SIZE) return -EINVAL; if (config->tbl_size[6] != GAMUT_T6_SIZE) return -EINVAL; if (config->tbl_size[7] != GAMUT_T7_SIZE) return -EINVAL; return 0; } int <API key>(struct mdp_gamut_cfg_data *config, u32 *copyback) { int i, j, ret = 0; u32 disp_num, dspp_num = 0; uint16_t *tbl_off; struct mdp_gamut_cfg_data local_cfg; uint16_t *r_tbl[MDP_GAMUT_TABLE_NUM]; uint16_t *g_tbl[MDP_GAMUT_TABLE_NUM]; uint16_t *b_tbl[MDP_GAMUT_TABLE_NUM]; char __iomem *addr; if ((config->block < <API key>) || (config->block >= MDP_BLOCK_MAX)) return -EINVAL; if (<API key>(config)) return -EINVAL; if ((config->flags & MDSS_PP_SPLIT_MASK) == MDSS_PP_SPLIT_MASK) { pr_warn("Can't set both split bits\n"); return -EINVAL; } mutex_lock(&mdss_pp_mutex); disp_num = config->block - <API key>; if (config->flags & MDP_PP_OPS_READ) { ret = pp_get_dspp_num(disp_num, &dspp_num); if (ret) { pr_err("%s, no dspp connects to disp %d", __func__, disp_num); goto gamut_config_exit; } mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_ON, false); addr = <API key>(dspp_num) + <API key>; for (i = 0; i < MDP_GAMUT_TABLE_NUM; i++) { r_tbl[i] = kzalloc( sizeof(uint16_t) * config->tbl_size[i], GFP_KERNEL); if (!r_tbl[i]) { pr_err("%s: alloc failed\n", __func__); goto gamut_config_exit; } for (j = 0; j < config->tbl_size[i]; j++) r_tbl[i][j] = (u16)readl_relaxed(addr); addr += 4; ret = copy_to_user(config->r_tbl[i], r_tbl[i], sizeof(uint16_t) * config->tbl_size[i]); kfree(r_tbl[i]); if (ret) { pr_err("%s: copy tbl to usr failed\n", __func__); goto gamut_config_exit; } } for (i = 0; i < MDP_GAMUT_TABLE_NUM; i++) { g_tbl[i] = kzalloc( sizeof(uint16_t) * config->tbl_size[i], GFP_KERNEL); if (!g_tbl[i]) { pr_err("%s: alloc failed\n", __func__); goto gamut_config_exit; } for (j = 0; j < config->tbl_size[i]; j++) g_tbl[i][j] = (u16)readl_relaxed(addr); addr += 4; ret = copy_to_user(config->g_tbl[i], g_tbl[i], sizeof(uint16_t) * config->tbl_size[i]); kfree(g_tbl[i]); if (ret) { pr_err("%s: copy tbl to usr failed\n", __func__); goto gamut_config_exit; } } for (i = 0; i < MDP_GAMUT_TABLE_NUM; i++) { b_tbl[i] = kzalloc( sizeof(uint16_t) * config->tbl_size[i], GFP_KERNEL); if (!b_tbl[i]) { pr_err("%s: alloc failed\n", __func__); goto gamut_config_exit; } for (j = 0; j < config->tbl_size[i]; j++) b_tbl[i][j] = (u16)readl_relaxed(addr); addr += 4; ret = copy_to_user(config->b_tbl[i], b_tbl[i], sizeof(uint16_t) * config->tbl_size[i]); kfree(b_tbl[i]); if (ret) { pr_err("%s: copy tbl to usr failed\n", __func__); goto gamut_config_exit; } } *copyback = 1; mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false); } else { local_cfg = *config; tbl_off = mdss_pp_res->gamut_tbl[disp_num]; for (i = 0; i < MDP_GAMUT_TABLE_NUM; i++) { local_cfg.r_tbl[i] = tbl_off; if (copy_from_user(tbl_off, config->r_tbl[i], config->tbl_size[i] * sizeof(uint16_t))) { ret = -EFAULT; goto gamut_config_exit; } tbl_off += local_cfg.tbl_size[i]; } for (i = 0; i < MDP_GAMUT_TABLE_NUM; i++) { local_cfg.g_tbl[i] = tbl_off; if (copy_from_user(tbl_off, config->g_tbl[i], config->tbl_size[i] * sizeof(uint16_t))) { ret = -EFAULT; goto gamut_config_exit; } tbl_off += local_cfg.tbl_size[i]; } for (i = 0; i < MDP_GAMUT_TABLE_NUM; i++) { local_cfg.b_tbl[i] = tbl_off; if (copy_from_user(tbl_off, config->b_tbl[i], config->tbl_size[i] * sizeof(uint16_t))) { ret = -EFAULT; goto gamut_config_exit; } tbl_off += local_cfg.tbl_size[i]; } mdss_pp_res->gamut_disp_cfg[disp_num] = local_cfg; mdss_pp_res->pp_disp_flags[disp_num] |= <API key>; } gamut_config_exit: mutex_unlock(&mdss_pp_mutex); return ret; } static u32 pp_hist_read(char __iomem *v_addr, struct pp_hist_col_info *hist_info) { int i, i_start; u32 sum = 0; u32 data; data = readl_relaxed(v_addr); i_start = data >> 24; hist_info->data[i_start] = data & 0xFFFFFF; sum += hist_info->data[i_start]; for (i = i_start + 1; i < HIST_V_SIZE; i++) { hist_info->data[i] = readl_relaxed(v_addr) & 0xFFFFFF; sum += hist_info->data[i]; } for (i = 0; i < i_start; i++) { hist_info->data[i] = readl_relaxed(v_addr) & 0xFFFFFF; sum += hist_info->data[i]; } hist_info->hist_cnt_read++; return sum; } /* Assumes that relevant clocks are enabled */ static int pp_histogram_enable(struct pp_hist_col_info *hist_info, struct <API key> *req, u32 shift_bit, char __iomem *ctl_base) { unsigned long flag; int ret = 0; struct mdss_data_type *mdata = mdss_mdp_get_mdata(); mutex_lock(&hist_info->hist_mutex); /* check if it is idle */ if (hist_info->col_en) { pr_info("%s Hist collection has already been enabled %d", __func__, (u32) ctl_base); ret = -EINVAL; goto exit; } hist_info->frame_cnt = req->frame_cnt; init_completion(&hist_info->comp); hist_info->hist_cnt_read = 0; hist_info->hist_cnt_sent = 0; hist_info->hist_cnt_time = 0; spin_lock_irqsave(&hist_info->hist_lock, flag); hist_info->read_request = 0; hist_info->col_state = HIST_RESET; hist_info->col_en = true; <API key>(&hist_info->hist_lock, flag); <API key>(&mdata->hist_intr, 3 << shift_bit, true); writel_relaxed(req->frame_cnt, ctl_base + 8); /* Kick out reset start */ writel_relaxed(1, ctl_base + 4); exit: mutex_unlock(&hist_info->hist_mutex); return ret; } #define <API key> 16777215 int mdss_mdp_hist_start(struct <API key> *req) { u32 done_shift_bit; char __iomem *ctl_base; struct pp_hist_col_info *hist_info; int i, ret = 0; u32 disp_num, dspp_num = 0; u32 mixer_cnt, mixer_id[<API key>]; u32 frame_size; struct mdss_mdp_pipe *pipe; struct mdss_data_type *mdata = mdss_mdp_get_mdata(); if (!mdss_is_ready()) return -EPROBE_DEFER; if ((PP_BLOCK(req->block) < <API key>) || (PP_BLOCK(req->block) >= MDP_BLOCK_MAX)) return -EINVAL; disp_num = PP_BLOCK(req->block) - <API key>; mixer_cnt = <API key>(disp_num, mixer_id); if (!mixer_cnt) { pr_err("%s, no dspp connects to disp %d", __func__, disp_num); ret = -EPERM; goto hist_exit; } if (mixer_cnt >= MDSS_MDP_MAX_DSPP) { pr_err("%s, Too many dspp connects to disp %d", __func__, mixer_cnt); ret = -EPERM; goto hist_exit; } frame_size = (mdata->ctl_off[mixer_id[0]].width * mdata->ctl_off[mixer_id[0]].height); if (!frame_size || ((<API key> / frame_size) < req->frame_cnt)) { pr_err("%s, too many frames for given display size, %d", __func__, req->frame_cnt); ret = -EINVAL; goto hist_exit; } mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_ON, false); if (PP_LOCAT(req->block) == MDSS_PP_SSPP_CFG) { i = MDSS_PP_ARG_MASK & req->block; if (!i) { ret = -EINVAL; pr_warn("Must pass pipe arguments, %d", i); goto hist_stop_clk; } for (i = 0; i < MDSS_PP_ARG_NUM; i++) { if (!PP_ARG(i, req->block)) continue; pipe = mdss_mdp_pipe_get(mdata, BIT(i)); if (IS_ERR_OR_NULL(pipe)) continue; if (!pipe || pipe->num > MDSS_MDP_SSPP_VIG2) { ret = -EINVAL; pr_warn("Invalid Hist pipe (%d)", i); goto hist_stop_clk; } done_shift_bit = (pipe->num * 4); hist_info = &pipe->pp_res.hist; ctl_base = pipe->base + <API key>; ret = pp_histogram_enable(hist_info, req, done_shift_bit, ctl_base); mdss_mdp_pipe_unmap(pipe); } } else if (PP_LOCAT(req->block) == MDSS_PP_DSPP_CFG) { for (i = 0; i < mixer_cnt; i++) { dspp_num = mixer_id[i]; done_shift_bit = (dspp_num * 4) + 12; hist_info = &mdss_pp_res->dspp_hist[dspp_num]; ctl_base = <API key>(dspp_num) + <API key>; ret = pp_histogram_enable(hist_info, req, done_shift_bit, ctl_base); mdss_pp_res->pp_disp_flags[disp_num] |= <API key>; } } hist_stop_clk: mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false); hist_exit: return ret; } static int <API key>(struct pp_hist_col_info *hist_info, u32 done_bit, char __iomem *ctl_base) { int ret = 0; unsigned long flag; struct mdss_data_type *mdata = mdss_mdp_get_mdata(); mutex_lock(&hist_info->hist_mutex); if (hist_info->col_en == false) { pr_debug("Histogram already disabled (%d)", (u32) ctl_base); ret = -EINVAL; goto exit; } complete_all(&hist_info->comp); spin_lock_irqsave(&hist_info->hist_lock, flag); hist_info->col_en = false; hist_info->col_state = HIST_UNKNOWN; <API key>(&hist_info->hist_lock, flag); <API key>(&mdata->hist_intr, done_bit, false); writel_relaxed(BIT(1), ctl_base);/* cancel */ ret = 0; exit: mutex_unlock(&hist_info->hist_mutex); return ret; } int mdss_mdp_hist_stop(u32 block) { int i, ret = 0; char __iomem *ctl_base; u32 dspp_num, disp_num, done_bit; struct pp_hist_col_info *hist_info; u32 mixer_cnt, mixer_id[<API key>]; struct mdss_mdp_pipe *pipe; struct mdss_data_type *mdata = mdss_mdp_get_mdata(); if ((PP_BLOCK(block) < <API key>) || (PP_BLOCK(block) >= MDP_BLOCK_MAX)) return -EINVAL; disp_num = PP_BLOCK(block) - <API key>; mixer_cnt = <API key>(disp_num, mixer_id); if (!mixer_cnt) { pr_err("%s, no dspp connects to disp %d", __func__, disp_num); ret = -EPERM; goto hist_stop_exit; } if (mixer_cnt >= MDSS_MDP_MAX_DSPP) { pr_err("%s, Too many dspp connects to disp %d", __func__, mixer_cnt); ret = -EPERM; goto hist_stop_exit; } mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_ON, false); if (PP_LOCAT(block) == MDSS_PP_SSPP_CFG) { i = MDSS_PP_ARG_MASK & block; if (!i) { pr_warn("Must pass pipe arguments, %d", i); goto hist_stop_clk; } for (i = 0; i < MDSS_PP_ARG_NUM; i++) { if (!PP_ARG(i, block)) continue; pipe = mdss_mdp_pipe_get(mdata, BIT(i)); if (IS_ERR_OR_NULL(pipe) || pipe->num > MDSS_MDP_SSPP_VIG2) { pr_warn("Invalid Hist pipe (%d)", i); continue; } done_bit = 3 << (pipe->num * 4); hist_info = &pipe->pp_res.hist; ctl_base = pipe->base + <API key>; ret = <API key>(hist_info, done_bit, ctl_base); mdss_mdp_pipe_unmap(pipe); if (ret) goto hist_stop_clk; } } else if (PP_LOCAT(block) == MDSS_PP_DSPP_CFG) { for (i = 0; i < mixer_cnt; i++) { dspp_num = mixer_id[i]; done_bit = 3 << ((dspp_num * 4) + 12); hist_info = &mdss_pp_res->dspp_hist[dspp_num]; ctl_base = <API key>(dspp_num) + <API key>; ret = <API key>(hist_info, done_bit, ctl_base); if (ret) goto hist_stop_clk; mdss_pp_res->pp_disp_flags[disp_num] |= <API key>; } } hist_stop_clk: mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false); hist_stop_exit: return ret; } /** * <API key>() - Request changes the histogram interupts * @intr: structure containting state of interrupt register * @bits: the bits on interrupt register that should be changed * @en: true if bits should be set, false if bits should be cleared * * Adds or removes the bits from the interrupt request. * * Does not store reference count for each bit. I.e. a bit with multiple * enable requests can be disabled with a single disable request. * * Return: 0 if uneventful, errno on invalid input */ int <API key>(struct mdss_intr *intr, u32 bits, bool en) { unsigned long flag; int ret = 0; if (!intr) { pr_err("NULL addr passed, %p", intr); return -EINVAL; } spin_lock_irqsave(&intr->lock, flag); if (en) intr->req |= bits; else intr->req &= ~bits; <API key>(&intr->lock, flag); <API key>(intr, MDSS_IRQ_REQ); return ret; } #define <API key> 1 #define <API key> 0 #define <API key> -1 /** * <API key>() - Manage intr and clk depending on requests. * @intr: structure containting state of intr reg * @state: MDSS_IRQ_SUSPEND if suspend is needed, * MDSS_IRQ_RESUME if resume is needed, * MDSS_IRQ_REQ if neither (i.e. requesting an interrupt) * * This function acts as a gatekeeper for the interrupt, making sure that the * MDP clocks are enabled while the interrupts are enabled to prevent * unclocked accesses. * * To reduce code repetition, 4 state transitions have been encoded here. Each * transition updates the interrupt's state structure (mdss_intr) to reflect * the which bits have been requested (intr->req), are currently enabled * (intr->curr), as well as defines which interrupt bits need to be enabled or * disabled ('en' and 'dis' respectively). The 4th state is not explicity * coded in the if/else chain, but is for MDSS_IRQ_REQ's when the interrupt * is in suspend, in which case, the only change required (intr->req being * updated) has already occured in the calling function. * * To control the clock, which can't be requested while holding the spinlock, * the inital state is compared with the exit state to detect when the * interrupt needs a clock. * * The clock requests surrounding the majority of this function serve to * enable the register writes to change the interrupt register, as well as to * prevent a race condition that could keep the clocks on (due to mdp_clk_cnt * never being decremented below 0) when a enable/disable occurs but the * disable requests the clocks disabled before the enable is able to request * the clocks enabled. * * Return: 0 if uneventful, errno on repeated action or invalid input */ int <API key>(struct mdss_intr *intr, int type) { unsigned long flag; int ret = 0, req_clk = 0; u32 en = 0, dis = 0; u32 diff, init_curr; int init_state; if (!intr) { WARN(1, "NULL intr pointer"); return -EINVAL; } mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_ON, false); spin_lock_irqsave(&intr->lock, flag); init_state = intr->state; init_curr = intr->curr; if (type == MDSS_IRQ_RESUME) { /* resume intrs */ if (intr->state == <API key>) { ret = -EPERM; goto exit; } en = intr->req; dis = 0; intr->curr = intr->req; intr->state = intr->curr ? <API key> : <API key>; } else if (type == MDSS_IRQ_SUSPEND) { /* suspend intrs */ if (intr->state == <API key>) { ret = -EPERM; goto exit; } en = 0; dis = intr->curr; intr->curr = 0; intr->state = <API key>; } else if (intr->state != MDSS_IRQ_SUSPEND) { /* Not resuming/suspending or in suspend state */ diff = intr->req ^ intr->curr; en = diff & ~intr->curr; dis = diff & ~intr->req; intr->curr = intr->req; intr->state = intr->curr ? <API key> : <API key>; } if (en) <API key>(en); if (dis) <API key>(dis); if ((init_state != <API key>) && (intr->state == <API key>)) req_clk = 1; else if ((init_state == <API key>) && (intr->state != <API key>)) req_clk = -1; exit: <API key>(&intr->lock, flag); if (req_clk < 0) mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false); else if (req_clk > 0) mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_ON, false); mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false); return ret; } static int pp_hist_collect(struct mdp_histogram_data *hist, struct pp_hist_col_info *hist_info, char __iomem *ctl_base, u32 expect_sum) { int wait_ret, ret = 0; u32 timeout, sum; char __iomem *v_base; unsigned long flag; struct mdss_pipe_pp_res *res; struct mdss_mdp_pipe *pipe; mutex_lock(&hist_info->hist_mutex); if ((hist_info->col_en == 0) || (hist_info->col_state == HIST_UNKNOWN)) { ret = -EINVAL; goto hist_collect_exit; } spin_lock_irqsave(&hist_info->hist_lock, flag); /* wait for hist done if cache has no data */ if (hist_info->col_state != HIST_READY) { <API key>(&hist_info->hist_lock, flag); timeout = HIST_WAIT_TIMEOUT(hist_info->frame_cnt); mutex_unlock(&hist_info->hist_mutex); if (PP_LOCAT(hist->block) == MDSS_PP_SSPP_CFG) { res = container_of(hist_info, struct mdss_pipe_pp_res, hist); pipe = container_of(res, struct mdss_mdp_pipe, pp_res); pipe->params_changed++; } wait_ret = <API key>( &(hist_info->comp), timeout); mutex_lock(&hist_info->hist_mutex); if (wait_ret == 0) { ret = -ETIMEDOUT; spin_lock_irqsave(&hist_info->hist_lock, flag); pr_debug("bin collection timedout, state %d", hist_info->col_state); /* * When the histogram has timed out (usually * underrun) change the SW state back to idle * since histogram hardware will have done the * same. Histogram data also needs to be * cleared in this case, which is done by the * histogram being read (triggered by READY * state, which also moves the histogram SW back * to IDLE). */ hist_info->hist_cnt_time++; hist_info->col_state = HIST_READY; <API key>(&hist_info->hist_lock, flag); } else if (wait_ret < 0) { ret = -EINTR; pr_debug("%s: bin collection interrupted", __func__); goto hist_collect_exit; } if (hist_info->col_state != HIST_READY) { ret = -ENODATA; spin_lock_irqsave(&hist_info->hist_lock, flag); hist_info->col_state = HIST_READY; <API key>(&hist_info->hist_lock, flag); pr_debug("%s: state is not ready: %d", __func__, hist_info->col_state); } } else { <API key>(&hist_info->hist_lock, flag); } spin_lock_irqsave(&hist_info->hist_lock, flag); if (hist_info->col_state == HIST_READY) { <API key>(&hist_info->hist_lock, flag); v_base = ctl_base + 0x1C; mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_ON, false); sum = pp_hist_read(v_base, hist_info); mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false); spin_lock_irqsave(&hist_info->hist_lock, flag); if (expect_sum && sum != expect_sum) ret = -ENODATA; hist_info->col_state = HIST_IDLE; } <API key>(&hist_info->hist_lock, flag); hist_collect_exit: mutex_unlock(&hist_info->hist_mutex); return ret; } int <API key>(struct mdp_histogram_data *hist) { int i, j, off, ret = 0, temp_ret = 0; struct pp_hist_col_info *hist_info; struct pp_hist_col_info *hists[<API key>]; u32 dspp_num, disp_num; char __iomem *ctl_base; u32 hist_cnt, mixer_id[<API key>]; u32 *hist_concat = NULL; u32 *hist_data_addr; u32 pipe_cnt = 0; u32 pipe_num = MDSS_MDP_SSPP_VIG0; u32 exp_sum = 0; struct mdss_mdp_pipe *pipe; struct mdss_data_type *mdata = mdss_mdp_get_mdata(); unsigned long flag; if ((PP_BLOCK(hist->block) < <API key>) || (PP_BLOCK(hist->block) >= MDP_BLOCK_MAX)) return -EINVAL; disp_num = PP_BLOCK(hist->block) - <API key>; hist_cnt = <API key>(disp_num, mixer_id); if (!hist_cnt) { pr_err("%s, no dspp connects to disp %d", __func__, disp_num); ret = -EPERM; goto hist_collect_exit; } if (hist_cnt >= MDSS_MDP_MAX_DSPP) { pr_err("%s, Too many dspp connects to disp %d", __func__, hist_cnt); ret = -EPERM; goto hist_collect_exit; } if (PP_LOCAT(hist->block) == MDSS_PP_DSPP_CFG) { for (i = 0; i < hist_cnt; i++) { dspp_num = mixer_id[i]; hists[i] = &mdss_pp_res->dspp_hist[dspp_num]; } for (i = 0; i < hist_cnt; i++) { spin_lock_irqsave(&hists[i]->hist_lock, flag); /* mark that collect is ready to handle completions */ hists[i]->read_request = 1; <API key>(&hists[i]->hist_lock, flag); } for (i = 0; i < hist_cnt; i++) { dspp_num = mixer_id[i]; ctl_base = <API key>(dspp_num) + <API key>; exp_sum = (mdata->mixer_intf[dspp_num].width * mdata->mixer_intf[dspp_num].height); if (ret) temp_ret = ret; ret = pp_hist_collect(hist, hists[i], ctl_base, exp_sum); } for (i = 0; i < hist_cnt; i++) { /* reset read requests and re-intialize completions */ spin_lock_irqsave(&hists[i]->hist_lock, flag); hists[i]->read_request = 0; INIT_COMPLETION(hists[i]->comp); <API key>(&hists[i]->hist_lock, flag); } if (ret || temp_ret) { ret = ret ? ret : temp_ret; goto hist_collect_exit; } if (hist->bin_cnt != HIST_V_SIZE) { pr_err("User not expecting size %d output", HIST_V_SIZE); ret = -EINVAL; goto hist_collect_exit; } if (hist_cnt > 1) { hist_concat = kmalloc(HIST_V_SIZE * sizeof(u32), GFP_KERNEL); if (!hist_concat) { ret = -ENOMEM; goto hist_collect_exit; } memset(hist_concat, 0, HIST_V_SIZE * sizeof(u32)); for (i = 0; i < hist_cnt; i++) { mutex_lock(&hists[i]->hist_mutex); for (j = 0; j < HIST_V_SIZE; j++) hist_concat[j] += hists[i]->data[j]; mutex_unlock(&hists[i]->hist_mutex); } hist_data_addr = hist_concat; } else { hist_data_addr = hists[0]->data; } for (i = 0; i < hist_cnt; i++) hists[i]->hist_cnt_sent++; } else if (PP_LOCAT(hist->block) == MDSS_PP_SSPP_CFG) { hist_cnt = MDSS_PP_ARG_MASK & hist->block; if (!hist_cnt) { pr_warn("Must pass pipe arguments, %d", hist_cnt); goto hist_collect_exit; } /* Find the first pipe requested */ for (i = 0; i < MDSS_PP_ARG_NUM; i++) { if (PP_ARG(i, hist_cnt)) { pipe_num = i; break; } } pipe = mdss_mdp_pipe_get(mdata, BIT(pipe_num)); if (IS_ERR_OR_NULL(pipe)) { pr_warn("Invalid starting hist pipe, %d", pipe_num); ret = -ENODEV; goto hist_collect_exit; } hist_info = &pipe->pp_res.hist; mdss_mdp_pipe_unmap(pipe); for (i = pipe_num; i < MDSS_PP_ARG_NUM; i++) { if (!PP_ARG(i, hist->block)) continue; pipe_cnt++; pipe = mdss_mdp_pipe_get(mdata, BIT(i)); if (IS_ERR_OR_NULL(pipe) || pipe->num > MDSS_MDP_SSPP_VIG2) { pr_warn("Invalid Hist pipe (%d)", i); continue; } hist_info = &pipe->pp_res.hist; spin_lock_irqsave(&hist_info->hist_lock, flag); hist_info->read_request = 1; <API key>(&hist_info->hist_lock, flag); } for (i = pipe_num; i < MDSS_PP_ARG_NUM; i++) { if (!PP_ARG(i, hist->block)) continue; pipe_cnt++; pipe = mdss_mdp_pipe_get(mdata, BIT(i)); if (IS_ERR_OR_NULL(pipe) || pipe->num > MDSS_MDP_SSPP_VIG2) { pr_warn("Invalid Hist pipe (%d)", i); continue; } hist_info = &pipe->pp_res.hist; ctl_base = pipe->base + <API key>; if (ret) temp_ret = ret; ret = pp_hist_collect(hist, hist_info, ctl_base, exp_sum); mdss_mdp_pipe_unmap(pipe); } for (i = pipe_num; i < MDSS_PP_ARG_NUM; i++) { if (!PP_ARG(i, hist->block)) continue; pipe_cnt++; pipe = mdss_mdp_pipe_get(mdata, BIT(i)); if (IS_ERR_OR_NULL(pipe) || pipe->num > MDSS_MDP_SSPP_VIG2) { pr_warn("Invalid Hist pipe (%d)", i); continue; } hist_info = &pipe->pp_res.hist; spin_lock_irqsave(&hist_info->hist_lock, flag); hist_info->read_request = 0; INIT_COMPLETION(hist_info->comp); <API key>(&hist_info->hist_lock, flag); } if (ret || temp_ret) { ret = ret ? ret : temp_ret; goto hist_collect_exit; } if (pipe_cnt != 0 && (hist->bin_cnt != (HIST_V_SIZE * pipe_cnt))) { pr_err("User not expecting size %d output", pipe_cnt * HIST_V_SIZE); ret = -EINVAL; goto hist_collect_exit; } if (pipe_cnt > 1) { hist_concat = kmalloc(HIST_V_SIZE * pipe_cnt * sizeof(u32), GFP_KERNEL); if (!hist_concat) { ret = -ENOMEM; goto hist_collect_exit; } memset(hist_concat, 0, pipe_cnt * HIST_V_SIZE * sizeof(u32)); for (i = pipe_num; i < MDSS_PP_ARG_NUM; i++) { if (!PP_ARG(i, hist->block)) continue; pipe = mdss_mdp_pipe_get(mdata, BIT(i)); hist_info = &pipe->pp_res.hist; off = HIST_V_SIZE * i; mutex_lock(&hist_info->hist_mutex); for (j = off; j < off + HIST_V_SIZE; j++) hist_concat[j] = hist_info->data[j - off]; hist_info->hist_cnt_sent++; mutex_unlock(&hist_info->hist_mutex); mdss_mdp_pipe_unmap(pipe); } hist_data_addr = hist_concat; } else { hist_data_addr = hist_info->data; } } else { pr_info("No Histogram at location %d", PP_LOCAT(hist->block)); goto hist_collect_exit; } ret = copy_to_user(hist->c0, hist_data_addr, sizeof(u32) * hist->bin_cnt); hist_collect_exit: kfree(hist_concat); return ret; } void <API key>(u32 isr) { u32 isr_blk, blk_idx; struct pp_hist_col_info *hist_info = NULL; struct mdss_mdp_pipe *pipe; struct mdss_data_type *mdata = mdss_mdp_get_mdata(); isr &= 0x333333; while (isr != 0) { if (isr & 0xFFF000) { if (isr & 0x3000) { blk_idx = 0; isr_blk = (isr >> 12) & 0x3; isr &= ~0x3000; } else if (isr & 0x30000) { blk_idx = 1; isr_blk = (isr >> 16) & 0x3; isr &= ~0x30000; } else { blk_idx = 2; isr_blk = (isr >> 20) & 0x3; isr &= ~0x300000; } hist_info = &mdss_pp_res->dspp_hist[blk_idx]; } else { if (isr & 0x3) { blk_idx = MDSS_MDP_SSPP_VIG0; isr_blk = isr & 0x3; isr &= ~0x3; } else if (isr & 0x30) { blk_idx = MDSS_MDP_SSPP_VIG1; isr_blk = (isr >> 4) & 0x3; isr &= ~0x30; } else { blk_idx = MDSS_MDP_SSPP_VIG2; isr_blk = (isr >> 8) & 0x3; isr &= ~0x300; } pipe = <API key>(mdata, BIT(blk_idx)); if (IS_ERR_OR_NULL(pipe)) { pr_debug("pipe DNE, %d", blk_idx); continue; } hist_info = &pipe->pp_res.hist; } /* Histogram Done Interrupt */ if (hist_info && (isr_blk & 0x1) && (hist_info->col_en)) { spin_lock(&hist_info->hist_lock); hist_info->col_state = HIST_READY; spin_unlock(&hist_info->hist_lock); if (hist_info->read_request == 1) { complete(&hist_info->comp); hist_info->read_request++; } } /* Histogram Reset Done Interrupt */ if ((isr_blk & 0x2) && (hist_info->col_en)) { spin_lock(&hist_info->hist_lock); hist_info->col_state = HIST_IDLE; spin_unlock(&hist_info->hist_lock); } }; } static struct msm_fb_data_type *<API key>(int index) { struct msm_fb_data_type *out = NULL; struct mdss_mdp_ctl *ctl; struct mdss_data_type *mdata = mdss_mdp_get_mdata(); int i; for (i = 0; i < mdata->nctl; i++) { ctl = mdata->ctl_off + i; if ((ctl->power_on) && (ctl->mfd) && (ctl->mfd->index == index)) out = ctl->mfd; } return out; } static int pp_num_to_side(struct mdss_mdp_ctl *ctl, u32 num) { u32 mixer_id[<API key>]; u32 mixer_num; if (!ctl || !ctl->mfd) return -EINVAL; mixer_num = <API key>(ctl->mfd->index, mixer_id); if (mixer_num < 2) return MDSS_SIDE_NONE; else if (mixer_id[1] == num) return MDSS_SIDE_RIGHT; else if (mixer_id[0] == num) return MDSS_SIDE_LEFT; else pr_err("invalid, not on any side"); return -EINVAL; } static inline void <API key>(u32 *sts, u32 bits) { u32 tmp = *sts; tmp &= ~MDSS_PP_SPLIT_MASK; tmp |= bits & MDSS_PP_SPLIT_MASK; *sts = tmp; } static inline bool pp_sts_is_enabled(u32 sts, int side) { bool ret = false; /* * If there are no sides, or if there are no split mode bits set, the * side can't be disabled via split mode. * * Otherwise, if the side being checked opposes the split mode * configuration, the side is disabled. */ if ((side == MDSS_SIDE_NONE) || !(sts & MDSS_PP_SPLIT_MASK)) ret = true; else if ((sts & <API key>) && (side == MDSS_SIDE_RIGHT)) ret = true; else if ((sts & <API key>) && (side == MDSS_SIDE_LEFT)) ret = true; return ret && (sts & PP_STS_ENABLE); } static int mdss_ad_init_checks(struct msm_fb_data_type *mfd) { u32 mixer_id[<API key>]; u32 mixer_num; u32 ret = -EINVAL; int i = 0; struct mdss_data_type *mdata = mfd_to_mdata(mfd); struct msm_fb_data_type *ad_mfd = mfd; if (ad_mfd->ext_ad_ctrl >= 0) ad_mfd = <API key>(ad_mfd->ext_ad_ctrl); if (!ad_mfd || !mdata) return ret; if (mdata->nad_cfgs == 0) { pr_debug("Assertive Display not supported by device"); return -ENODEV; } mixer_num = <API key>(ad_mfd->index, mixer_id); if (!mixer_num) { pr_debug("no mixers connected, %d", mixer_num); return -EHOSTDOWN; } if (mixer_num > mdata-><API key>) { pr_debug("too many mixers, not supported, %d > %d", mixer_num, mdata-><API key>); return ret; } do { if (mixer_id[i] >= mdata->nad_cfgs) { pr_err("invalid mixer input, %d", mixer_id[i]); return ret; } i++; } while (i < mixer_num); return mixer_id[0]; } static int mdss_mdp_get_ad(struct msm_fb_data_type *mfd, struct mdss_ad_info **ret_ad) { int ad_num, ret = 0; struct mdss_data_type *mdata; struct mdss_ad_info *ad = NULL; mdata = mfd_to_mdata(mfd); ad_num = mdss_ad_init_checks(mfd); if (ad_num >= 0) ad = &mdata->ad_cfgs[ad_num]; else ret = ad_num; *ret_ad = ad; return ret; } static int pp_update_ad_input(struct msm_fb_data_type *mfd) { int ret; struct mdss_ad_info *ad; struct mdss_ad_input input; struct mdss_mdp_ctl *ctl; if (!mfd) return -EINVAL; ctl = mfd_to_ctl(mfd); if (!ctl) return -EINVAL; ret = mdss_mdp_get_ad(mfd, &ad); if (ret) return ret; if (!ad || ad->cfg.mode == <API key>) return -EINVAL; pr_debug("backlight level changed (%d), trigger update to AD", mfd->bl_level); input.mode = ad->cfg.mode; if (<API key>(ad->cfg.mode, <API key>)) input.in.amb_light = ad->ad_data; else input.in.strength = ad->ad_data; /* call to ad_input will trigger backlight read */ return mdss_mdp_ad_input(mfd, &input, 0); } int mdss_mdp_ad_config(struct msm_fb_data_type *mfd, struct mdss_ad_init_cfg *init_cfg) { struct mdss_ad_info *ad; struct msm_fb_data_type *bl_mfd; int lin_ret = -1, inv_ret = -1, ret = 0; u32 ratio_temp, shift = 0, last_ops; ret = mdss_mdp_get_ad(mfd, &ad); if (ret) return ret; if (mfd->panel_info->type == WRITEBACK_PANEL) { bl_mfd = <API key>(0); if (!bl_mfd) return ret; } else { bl_mfd = mfd; } if ((init_cfg->ops & MDSS_PP_SPLIT_MASK) == MDSS_PP_SPLIT_MASK) { pr_warn("Can't set both split bits\n"); return -EINVAL; } mutex_lock(&ad->lock); if (init_cfg->ops & MDP_PP_AD_INIT) { memcpy(&ad->init, &init_cfg->params.init, sizeof(struct mdss_ad_init)); if (init_cfg->params.init.bl_lin_len == AD_BL_LIN_LEN) { lin_ret = copy_from_user(&ad->bl_lin, init_cfg->params.init.bl_lin, init_cfg->params.init.bl_lin_len * sizeof(uint32_t)); inv_ret = copy_from_user(&ad->bl_lin_inv, init_cfg->params.init.bl_lin_inv, init_cfg->params.init.bl_lin_len * sizeof(uint32_t)); if (lin_ret || inv_ret) ret = -ENOMEM; ratio_temp = mfd->panel_info->bl_max / AD_BL_LIN_LEN; while (ratio_temp > 0) { ratio_temp = ratio_temp >> 1; shift++; } ad->bl_bright_shift = shift; } else { ret = -EINVAL; } if (ret) { ad->state &= ~PP_AD_STATE_BL_LIN; goto ad_config_exit; } else ad->state |= PP_AD_STATE_BL_LIN; ad->sts |= <API key>; } else if (init_cfg->ops & MDP_PP_AD_CFG) { memcpy(&ad->cfg, &init_cfg->params.cfg, sizeof(struct mdss_ad_cfg)); /* * TODO: specify panel independent range of input from cfg, * scale input backlight_scale to panel bl_max's range */ ad->cfg.backlight_scale = bl_mfd->panel_info->bl_max; ad->sts |= PP_AD_STS_DIRTY_CFG; } last_ops = ad->ops & MDSS_PP_SPLIT_MASK; ad->ops = init_cfg->ops & MDSS_PP_SPLIT_MASK; /* * if there is a change in the split mode config, the init values * need to be re-written to hardware (if they have already been * written or if there is data pending to be written). Check for * pending data (DIRTY_INIT) is not checked here since it will not * affect the outcome of this conditional (i.e. if init hasn't * already been written (*_STATE_INIT is set), this conditional will * only evaluate to true (and set the DIRTY bit) if the DIRTY bit has * already been set). */ if ((last_ops ^ ad->ops) && (ad->state & PP_AD_STATE_INIT)) ad->sts |= <API key>; if (!ret && (init_cfg->ops & MDP_PP_OPS_DISABLE)) { ad->sts &= ~PP_STS_ENABLE; mutex_unlock(&ad->lock); cancel_work_sync(&ad->calc_work); mutex_lock(&ad->lock); ad->mfd = NULL; ad->bl_mfd = NULL; } else if (!ret && (init_cfg->ops & MDP_PP_OPS_ENABLE)) { ad->sts |= PP_STS_ENABLE; ad->mfd = mfd; ad->bl_mfd = bl_mfd; } ad_config_exit: mutex_unlock(&ad->lock); return ret; } int mdss_mdp_ad_input(struct msm_fb_data_type *mfd, struct mdss_ad_input *input, int wait) { int ret = 0; struct mdss_ad_info *ad; u32 bl; ret = mdss_mdp_get_ad(mfd, &ad); if (ret) return ret; mutex_lock(&ad->lock); if ((!<API key>(ad->state) && !PP_AD_STS_IS_DIRTY(ad->sts)) && !input->mode == MDSS_AD_MODE_CALIB) { pr_warn("AD not initialized or configured."); ret = -EPERM; goto error; } switch (input->mode) { case <API key>: case <API key>: if (!<API key>(ad->cfg.mode, <API key>)) { ret = -EINVAL; goto error; } if (input->in.amb_light > MDSS_MDP_MAX_AD_AL) { pr_warn("invalid input ambient light"); ret = -EINVAL; goto error; } ad->ad_data_mode = <API key>; pr_debug("ambient = %d", input->in.amb_light); ad->ad_data = input->in.amb_light; ad->calc_itr = ad->cfg.stab_itr; ad->sts |= <API key>; ad->sts |= <API key>; break; case <API key>: case <API key>: if (!<API key>(ad->cfg.mode, <API key>)) { ret = -EINVAL; goto error; } if (input->in.strength > MDSS_MDP_MAX_AD_STR) { pr_warn("invalid input strength"); ret = -EINVAL; goto error; } ad->ad_data_mode = <API key>; pr_debug("strength = %d", input->in.strength); ad->ad_data = input->in.strength; ad->calc_itr = ad->cfg.stab_itr; ad->sts |= <API key>; ad->sts |= <API key>; break; case MDSS_AD_MODE_CALIB: wait = 0; if (mfd->calib_mode) { bl = input->in.calib_bl; if (bl >= AD_BL_LIN_LEN) { pr_warn("calib_bl 255 max!"); break; } mutex_unlock(&ad->lock); mutex_lock(&mfd->bl_lock); MDSS_BRIGHT_TO_BL(bl, bl, mfd->panel_info->bl_max, mfd->panel_info->brightness_max); <API key>(mfd, bl); mutex_unlock(&mfd->bl_lock); mutex_lock(&ad->lock); } else { pr_warn("should be in calib mode"); } break; default: pr_warn("invalid default %d", input->mode); ret = -EINVAL; goto error; } error: mutex_unlock(&ad->lock); if (!ret) { if (wait) { mutex_lock(&ad->lock); init_completion(&ad->comp); mutex_unlock(&ad->lock); } if (wait) { ret = <API key>( &ad->comp, HIST_WAIT_TIMEOUT(1)); if (ret == 0) ret = -ETIMEDOUT; else if (ret > 0) input->output = ad->last_str; } } return ret; } static void pp_ad_input_write(struct mdss_mdp_ad *ad_hw, struct mdss_ad_info *ad) { char __iomem *base; base = ad_hw->base; switch (ad->cfg.mode) { case <API key>: writel_relaxed(ad->ad_data, base + MDSS_MDP_REG_AD_AL); break; case <API key>: writel_relaxed(ad->bl_data, base + MDSS_MDP_REG_AD_BL); writel_relaxed(ad->ad_data, base + MDSS_MDP_REG_AD_AL); break; case <API key>: writel_relaxed(ad->bl_data, base + MDSS_MDP_REG_AD_BL); writel_relaxed(ad->ad_data, base + <API key>); break; case <API key>: writel_relaxed(ad->bl_data, base + MDSS_MDP_REG_AD_BL); writel_relaxed(ad->ad_data, base + <API key>); break; default: pr_warn("Invalid mode! %d", ad->cfg.mode); break; } } #define <API key> 4 static void pp_ad_init_write(struct mdss_mdp_ad *ad_hw, struct mdss_ad_info *ad, struct mdss_mdp_ctl *ctl) { struct mdss_data_type *mdata = ctl->mdata; u32 temp; u32 frame_start, frame_end, procs_start, procs_end, tile_ctrl; u32 num; int side; char __iomem *base; bool is_calc, is_dual_pipe, split_mode; u32 mixer_id[<API key>]; u32 mixer_num; mixer_num = <API key>(ctl->mfd->index, mixer_id); if (mixer_num > 1) is_dual_pipe = true; else is_dual_pipe = false; base = ad_hw->base; is_calc = ad->calc_hw_num == ad_hw->num; split_mode = !!(ad->ops & MDSS_PP_SPLIT_MASK); writel_relaxed(ad->init.i_control[0] & 0x1F, base + <API key>); writel_relaxed(ad->init.i_control[1] << 8, base + <API key>); temp = ad->init.white_lvl << 16; temp |= ad->init.black_lvl & 0xFFFF; writel_relaxed(temp, base + <API key>); writel_relaxed(ad->init.var, base + MDSS_MDP_REG_AD_VAR); writel_relaxed(ad->init.limit_ampl, base + <API key>); writel_relaxed(ad->init.i_dither, base + <API key>); temp = ad->init.slope_max << 8; temp |= ad->init.slope_min & 0xFF; writel_relaxed(temp, base + <API key>); writel_relaxed(ad->init.dither_ctl, base + <API key>); writel_relaxed(ad->init.format, base + <API key>); writel_relaxed(ad->init.auto_size, base + <API key>); if (split_mode) temp = mdata->mixer_intf[ad_hw->num].width << 16; else temp = ad->init.frame_w << 16; temp |= ad->init.frame_h & 0xFFFF; writel_relaxed(temp, base + <API key>); temp = ad->init.logo_v << 8; temp |= ad->init.logo_h & 0xFF; writel_relaxed(temp, base + <API key>); pp_ad_cfg_lut(base + <API key>, ad->init.asym_lut); pp_ad_cfg_lut(base + <API key>, ad->init.color_corr_lut); if (mdata->mdp_rev >= MDSS_MDP_HW_REV_103) { if (is_dual_pipe && !split_mode) { num = ad_hw->num; side = pp_num_to_side(ctl, num); tile_ctrl = 0x5; if ((ad->calc_hw_num + 1) == num) tile_ctrl |= 0x10; if (side <= MDSS_SIDE_NONE) { WARN(1, "error finding sides, %d", side); frame_start = 0; procs_start = frame_start; frame_end = 0; procs_end = frame_end; } else if (side == MDSS_SIDE_LEFT) { frame_start = 0; procs_start = 0; frame_end = mdata->mixer_intf[num].width + <API key>; procs_end = mdata->mixer_intf[num].width; } else { procs_start = ad->init.frame_w - (mdata->mixer_intf[num].width); procs_end = ad->init.frame_w; frame_start = procs_start - <API key>; frame_end = procs_end; } procs_end -= 1; frame_end -= 1; } else { frame_start = 0x0; frame_end = 0xFFFF; procs_start = 0x0; procs_end = 0xFFFF; if (split_mode) tile_ctrl = 0x0; else tile_ctrl = 0x1; } writel_relaxed(frame_start, base + <API key>); writel_relaxed(frame_end, base + <API key>); writel_relaxed(procs_start, base + <API key>); writel_relaxed(procs_end, base + <API key>); writel_relaxed(tile_ctrl, base + <API key>); } } #define <API key> 0x6E static void pp_ad_cfg_write(struct mdss_mdp_ad *ad_hw, struct mdss_ad_info *ad) { char __iomem *base; u32 temp, temp_calib = <API key>; base = ad_hw->base; switch (ad->cfg.mode) { case <API key>: temp = ad->cfg.backlight_max << 16; temp |= ad->cfg.backlight_min & 0xFFFF; writel_relaxed(temp, base + <API key>); writel_relaxed(ad->cfg.amb_light_min, base + <API key>); temp = ad->cfg.filter[1] << 16; temp |= ad->cfg.filter[0] & 0xFFFF; writel_relaxed(temp, base + <API key>); case <API key>: pp_ad_cfg_lut(base + <API key>, ad->cfg.al_calib_lut); writel_relaxed(ad->cfg.strength_limit, base + <API key>); temp = ad->cfg.calib[3] << 16; temp |= ad->cfg.calib[2] & 0xFFFF; writel_relaxed(temp, base + <API key>); writel_relaxed(ad->cfg.t_filter_recursion, base + <API key>); temp_calib = ad->cfg.calib[0] & 0xFFFF; case <API key>: temp = ad->cfg.calib[1] << 16; temp |= temp_calib; writel_relaxed(temp, base + <API key>); case <API key>: writel_relaxed(ad->cfg.backlight_scale, base + <API key>); writel_relaxed(ad->cfg.mode, base + <API key>); pr_debug("stab_itr = %d", ad->cfg.stab_itr); break; default: break; } } static void pp_ad_vsync_handler(struct mdss_mdp_ctl *ctl, ktime_t t) { struct mdss_data_type *mdata = ctl->mdata; struct mdss_ad_info *ad; if (ctl->mixer_left && ctl->mixer_left->num < mdata->nad_cfgs) { ad = &mdata->ad_cfgs[ctl->mixer_left->num]; queue_work(mdata->ad_calc_wq, &ad->calc_work); } } #define <API key> 0x101 static void pp_ad_bypass_config(struct mdss_ad_info *ad, struct mdss_mdp_ctl *ctl, u32 num, u32 *opmode) { int side = pp_num_to_side(ctl, num); if (pp_sts_is_enabled(ad->reg_sts | (ad->ops & MDSS_PP_SPLIT_MASK), side)) { *opmode = 0; } else { *opmode = <API key>; } } static int pp_ad_setup_hw_nums(struct msm_fb_data_type *mfd, struct mdss_ad_info *ad) { u32 mixer_id[<API key>]; u32 mixer_num; mixer_num = <API key>(mfd->index, mixer_id); if (!mixer_num) return -EINVAL; /* default to left mixer */ ad->calc_hw_num = mixer_id[0]; if ((mixer_num > 1) && (ad->ops & <API key>)) ad->calc_hw_num = mixer_id[1]; return 0; } static int mdss_mdp_ad_setup(struct msm_fb_data_type *mfd) { int ret = 0; struct mdss_ad_info *ad; struct mdss_mdp_ctl *ctl = mfd_to_ctl(mfd); struct msm_fb_data_type *bl_mfd; struct mdss_data_type *mdata; u32 bypass = <API key>, bl; ret = mdss_mdp_get_ad(mfd, &ad); if (ret) { ret = -EINVAL; pr_debug("failed to get ad_info, err = %d", ret); goto exit; } if (mfd->panel_info->type == WRITEBACK_PANEL) { bl_mfd = <API key>(0); if (!bl_mfd) { ret = -EINVAL; pr_warn("failed to get primary FB bl handle, err = %d", ret); goto exit; } } else { bl_mfd = mfd; } mdata = mfd_to_mdata(mfd); mutex_lock(&ad->lock); if (ad->sts != last_sts || ad->state != last_state) { last_sts = ad->sts; last_state = ad->state; pr_debug("begining: ad->sts = 0x%08x, state = 0x%08x", ad->sts, ad->state); } if (!PP_AD_STS_IS_DIRTY(ad->sts) && (ad->sts & <API key>)) { /* * Write inputs to regs when the data has been updated or * Assertive Display is up and running as long as there are * no updates to AD init or cfg */ ad->sts &= ~<API key>; ad->state |= PP_AD_STATE_DATA; mutex_lock(&bl_mfd->bl_lock); bl = bl_mfd->bl_level; pr_debug("dirty data, last_bl = %d ", ad->last_bl); if ((ad->cfg.mode == <API key>) && (ad->last_bl != bl)) { ad->last_bl = bl; ad->calc_itr = ad->cfg.stab_itr; ad->sts |= <API key>; if (ad->state & PP_AD_STATE_BL_LIN) { bl = ad->bl_lin[bl >> ad->bl_bright_shift]; bl = bl << ad->bl_bright_shift; } ad->bl_data = bl; } mutex_unlock(&bl_mfd->bl_lock); ad->reg_sts |= <API key>; } if (ad->sts & PP_AD_STS_DIRTY_CFG) { ad->sts &= ~PP_AD_STS_DIRTY_CFG; ad->state |= PP_AD_STATE_CFG; ad->reg_sts |= PP_AD_STS_DIRTY_CFG; if (!<API key>(ad->cfg.mode, ad->ad_data_mode)) { ad->sts &= ~<API key>; ad->state &= ~PP_AD_STATE_DATA; pr_debug("Mode switched, data invalidated!"); } } if (ad->sts & <API key>) { ad->sts &= ~<API key>; if (pp_ad_setup_hw_nums(mfd, ad)) { pr_warn("failed to setup ad master"); ad->calc_hw_num = PP_AD_BAD_HW_NUM; } else { ad->state |= PP_AD_STATE_INIT; ad->reg_sts |= <API key>; } } /* update ad screen size if it has changed since last configuration */ if (mfd->panel_info->type == WRITEBACK_PANEL && (ad->init.frame_w != ctl->width || ad->init.frame_h != ctl->height)) { pr_debug("changing from %dx%d to %dx%d", ad->init.frame_w, ad->init.frame_h, ctl->width, ctl->height); ad->init.frame_w = ctl->width; ad->init.frame_h = ctl->height; ad->reg_sts |= <API key>; } if ((ad->sts & PP_STS_ENABLE) && <API key>(ad->state)) { bypass = 0; ad->reg_sts |= <API key>; ad->state |= PP_AD_STATE_RUN; mutex_lock(&bl_mfd->bl_lock); if (bl_mfd != mfd) bl_mfd->ext_ad_ctrl = mfd->index; bl_mfd->mdp.update_ad_input = pp_update_ad_input; bl_mfd->ext_bl_ctrl = ad->cfg.bl_ctrl_mode; mutex_unlock(&bl_mfd->bl_lock); } else { if (ad->state & PP_AD_STATE_RUN) { ad->reg_sts = <API key>; /* Clear state and regs when going to off state*/ ad->sts = 0; ad->sts |= <API key>; ad->state &= !PP_AD_STATE_INIT; ad->state &= !PP_AD_STATE_CFG; ad->state &= !PP_AD_STATE_DATA; ad->state &= !PP_AD_STATE_BL_LIN; ad->bl_bright_shift = 0; ad->ad_data = 0; ad->ad_data_mode = 0; ad->last_bl = 0; ad->calc_itr = 0; ad->calc_hw_num = PP_AD_BAD_HW_NUM; memset(&ad->bl_lin, 0, sizeof(uint32_t) * AD_BL_LIN_LEN); memset(&ad->bl_lin_inv, 0, sizeof(uint32_t) * AD_BL_LIN_LEN); memset(&ad->init, 0, sizeof(struct mdss_ad_init)); memset(&ad->cfg, 0, sizeof(struct mdss_ad_cfg)); mutex_lock(&bl_mfd->bl_lock); bl_mfd->mdp.update_ad_input = NULL; bl_mfd->ext_bl_ctrl = 0; bl_mfd->ext_ad_ctrl = -1; mutex_unlock(&bl_mfd->bl_lock); } ad->state &= ~PP_AD_STATE_RUN; } if (!bypass) ad->reg_sts |= PP_STS_ENABLE; else ad->reg_sts &= ~PP_STS_ENABLE; if (<API key> & ad->sts) { pr_debug("dirty vsync, calc_itr = %d", ad->calc_itr); ad->sts &= ~<API key>; if (!(PP_AD_STATE_VSYNC & ad->state) && ad->calc_itr && (ad->state & PP_AD_STATE_RUN)) { ctl->add_vsync_handler(ctl, &ad->handle); ad->state |= PP_AD_STATE_VSYNC; } else if ((PP_AD_STATE_VSYNC & ad->state) && (!ad->calc_itr || !(PP_AD_STATE_RUN & ad->state))) { ctl-><API key>(ctl, &ad->handle); ad->state &= ~PP_AD_STATE_VSYNC; } } if (ad->sts != last_sts || ad->state != last_state) { last_sts = ad->sts; last_state = ad->state; pr_debug("end: ad->sts = 0x%08x, state = 0x%08x", ad->sts, ad->state); } mutex_unlock(&ad->lock); exit: return ret; } #define MDSS_PP_AD_SLEEP 10 static void pp_ad_calc_worker(struct work_struct *work) { struct mdss_ad_info *ad; struct mdss_mdp_ctl *ctl; struct msm_fb_data_type *mfd, *bl_mfd; struct mdss_data_type *mdata; char __iomem *base; u32 bl, calc_done = 0; ad = container_of(work, struct mdss_ad_info, calc_work); mutex_lock(&ad->lock); if (!ad->mfd || !ad->bl_mfd || !(ad->sts & PP_STS_ENABLE)) { mutex_unlock(&ad->lock); return; } mfd = ad->mfd; bl_mfd = ad->bl_mfd; ctl = mfd_to_ctl(ad->mfd); mdata = mfd_to_mdata(ad->mfd); if (!mdata || ad->calc_hw_num >= mdata->nad_cfgs) { mutex_unlock(&ad->lock); return; } base = mdata->ad_off[ad->calc_hw_num].base; if ((ad->cfg.mode == <API key>) && (ad->last_bl == 0)) { mutex_unlock(&ad->lock); return; } mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_ON, false); if (PP_AD_STATE_RUN & ad->state) { /* Kick off calculation */ ad->calc_itr writel_relaxed(1, base + <API key>); } if (ad->state & PP_AD_STATE_RUN) { do { calc_done = readl_relaxed(base + <API key>); if (!calc_done) usleep(MDSS_PP_AD_SLEEP); } while (!calc_done && (ad->state & PP_AD_STATE_RUN)); if (calc_done) { ad->last_str = 0xFF & readl_relaxed(base + <API key>); if (<API key>(ad)) { bl = 0xFFFF & readl_relaxed(base + <API key>); if (ad->state & PP_AD_STATE_BL_LIN) { bl = bl >> ad->bl_bright_shift; bl = min_t(u32, bl, (AD_BL_LIN_LEN-1)); bl = ad->bl_lin_inv[bl]; bl = bl << ad->bl_bright_shift; } pr_debug("calc bl = %d", bl); ad->last_str |= bl << 16; mutex_lock(&ad->bl_mfd->bl_lock); if (ad->bl_mfd->bl_level) <API key>(ad->bl_mfd, bl); mutex_unlock(&ad->bl_mfd->bl_lock); } pr_debug("calc_str = %d, calc_itr %d", ad->last_str & 0xFF, ad->calc_itr); } else { ad->last_str = 0xFFFFFFFF; } } mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false); complete(&ad->comp); if (!ad->calc_itr) { ad->state &= ~PP_AD_STATE_VSYNC; ctl-><API key>(ctl, &ad->handle); } mutex_unlock(&ad->lock); mutex_lock(&mfd->lock); ctl->flush_bits |= BIT(13 + ad->num); mutex_unlock(&mfd->lock); /* Trigger update notify to wake up those waiting for display updates */ <API key>(bl_mfd); } #define PP_AD_LUT_LEN 33 static void pp_ad_cfg_lut(char __iomem *addr, u32 *data) { int i; u32 temp; for (i = 0; i < PP_AD_LUT_LEN - 1; i += 2) { temp = data[i+1] << 16; temp |= (data[i] & 0xFFFF); writel_relaxed(temp, addr + (i*2)); } writel_relaxed(data[PP_AD_LUT_LEN - 1] << 16, addr + ((PP_AD_LUT_LEN - 1) * 2)); } int <API key>(struct mdss_data_type *mdata, u32 *ad_offsets) { u32 i; int rc = 0; mdata->ad_off = devm_kzalloc(&mdata->pdev->dev, sizeof(struct mdss_mdp_ad) * mdata->nad_cfgs, GFP_KERNEL); if (!mdata->ad_off) { pr_err("unable to setup assertive display hw:devm_kzalloc fail\n"); return -ENOMEM; } mdata->ad_cfgs = devm_kzalloc(&mdata->pdev->dev, sizeof(struct mdss_ad_info) * mdata->nad_cfgs, GFP_KERNEL); if (!mdata->ad_cfgs) { pr_err("unable to setup assertive display:devm_kzalloc fail\n"); devm_kfree(&mdata->pdev->dev, mdata->ad_off); return -ENOMEM; } mdata->ad_calc_wq = <API key>("ad_calc_wq"); for (i = 0; i < mdata->nad_cfgs; i++) { mdata->ad_off[i].base = mdata->mdp_base + ad_offsets[i]; mdata->ad_off[i].num = i; mdata->ad_cfgs[i].num = i; mdata->ad_cfgs[i].ops = 0; mdata->ad_cfgs[i].reg_sts = 0; mdata->ad_cfgs[i].calc_itr = 0; mdata->ad_cfgs[i].last_str = 0xFFFFFFFF; mdata->ad_cfgs[i].last_bl = 0; mutex_init(&mdata->ad_cfgs[i].lock); mdata->ad_cfgs[i].handle.vsync_handler = pp_ad_vsync_handler; mdata->ad_cfgs[i].handle.cmd_post_flush = true; INIT_WORK(&mdata->ad_cfgs[i].calc_work, pp_ad_calc_worker); } return rc; } static int <API key>(char __iomem *ptr) { char __iomem *base; int ret = 0, counter = 0; int stage = 0; struct mdss_mdp_ctl *ctl; /* Controller */ for (counter = 0; counter < mdss_res->nctl; counter++) { ctl = mdss_res->ctl_off + counter; base = ctl->base; if (ptr == base + <API key>) { ret = MDP_PP_OPS_READ; break; } else if (ptr == base + <API key>) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; } for (stage = 0; stage < mdss_res->nmixers_intf; stage++) if (ptr == base + <API key>(stage)) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; goto End; } } End: return ret; } static int <API key>(char __iomem *ptr) { char __iomem *base; int ret = 0, counter = 0; struct mdss_mdp_mixer *mixer; for (counter = 0; counter < mdss_res->nmixers_intf; counter++) { mixer = mdss_res->mixer_intf + counter; base = mixer->dspp_base; if (ptr == base) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; /* PA range */ } else if ((ptr >= base + <API key>) && (ptr <= base + <API key> + MDSS_MDP_PA_SIZE)) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; /* PCC range */ } else if ((ptr >= base + <API key>) && (ptr <= base + <API key> + MDSS_MDP_PCC_SIZE)) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; /* Gamut range */ } else if ((ptr >= base + <API key>) && (ptr <= base + <API key> + MDSS_MDP_GAMUT_SIZE)) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; /* GC range */ } else if ((ptr >= base + <API key>) && (ptr <= base + <API key> + MDSS_MDP_GC_SIZE)) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; /* Dither enable/disable */ } else if ((ptr == base + <API key>)) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; /* Six zone and mem color */ } else if (mdss_res->mdp_rev >= MDSS_MDP_HW_REV_103 && (ptr >= base + <API key>) && (ptr <= base + <API key> + <API key> + <API key>)) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; } } return ret; } static int <API key>(char __iomem *ptr) { char __iomem *base; int ret = 0, counter = 0; struct mdss_mdp_pipe *pipe; for (counter = 0; counter < mdss_res->nvig_pipes; counter++) { pipe = mdss_res->vig_pipes + counter; base = pipe->base; if (ptr == base + <API key>) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; } else if (ptr == base + <API key>) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; } else if (ptr == base + <API key>) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; } else if (ptr == base + <API key>) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; } else if (ptr == base + <API key>) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; } else if ((ptr == base + <API key>)) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; /* PA range */ } else if ((ptr >= base + <API key>) && (ptr <= base + <API key> + MDSS_MDP_PA_SIZE)) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; /* Mem color range */ } else if (mdss_res->mdp_rev >= MDSS_MDP_HW_REV_103 && (ptr >= base + <API key>) && (ptr <= base + <API key> + <API key>)) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; } } return ret; } static int <API key>(char __iomem *ptr) { char __iomem *base; int ret = 0, counter = 0; struct mdss_mdp_pipe *pipe; for (counter = 0; counter < mdss_res->nrgb_pipes; counter++) { pipe = mdss_res->rgb_pipes + counter; base = pipe->base; if (ptr == base + <API key>) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; } else if (ptr == base + <API key>) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; } else if (ptr == base + <API key>) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; } else if (ptr == base + <API key>) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; } } return ret; } static int <API key>(char __iomem *ptr) { char __iomem *base; int ret = 0, counter = 0; struct mdss_mdp_pipe *pipe; for (counter = 0; counter < mdss_res->ndma_pipes; counter++) { pipe = mdss_res->dma_pipes + counter; base = pipe->base; if (ptr == base + <API key>) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; } else if (ptr == base + <API key>) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; } else if (ptr == base + <API key>) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; } else if (ptr == base + <API key>) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; } } return ret; } static int <API key>(char __iomem *ptr) { char __iomem *base; int ret = 0, counter = 0; int stage = 0; struct mdss_mdp_mixer *mixer; for (counter = 0; counter < mdss_res->nmixers_intf; counter++) { mixer = mdss_res->mixer_intf + counter; base = mixer->base; if (ptr == base + <API key>) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; /* GC range */ } else if ((ptr >= base + <API key>) && (ptr <= base + <API key> + MDSS_MDP_GC_SIZE)) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; break; } for (stage = 0; stage < TOTAL_BLEND_STAGES; stage++) if (ptr == base + <API key>(stage) + <API key>) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; goto End; } else if (ptr == base + <API key>(stage) + <API key>) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; goto End; } else if (ptr == base + <API key>(stage) + <API key>) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; goto End; } } End: return ret; } static int is_valid_calib_addr(void *addr, u32 operation) { int ret = 0; char __iomem *ptr = addr; char __iomem *mixer_base = mdss_res->mixer_intf->base; char __iomem *rgb_base = mdss_res->rgb_pipes->base; char __iomem *dma_base = mdss_res->dma_pipes->base; char __iomem *vig_base = mdss_res->vig_pipes->base; char __iomem *ctl_base = mdss_res->ctl_off->base; char __iomem *dspp_base = mdss_res->mixer_intf->dspp_base; if ((unsigned int)addr % 4) { ret = 0; } else if (ptr == (mdss_res->mdp_base + <API key>) || ptr == (mdss_res->mdp_base + <API key>)) { ret = MDP_PP_OPS_READ; /* IGC DSPP range */ } else if (ptr >= (mdss_res->mdp_base + <API key>) && ptr <= (mdss_res->mdp_base + <API key> + <API key>)) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; /* IGC SSPP range */ } else if (ptr >= (mdss_res->mdp_base + <API key>) && ptr <= (mdss_res->mdp_base + <API key> + <API key>)) { ret = MDP_PP_OPS_READ | MDP_PP_OPS_WRITE; } else if (ptr >= dspp_base && ptr < (dspp_base + (mdss_res->nmixers_intf * <API key>))) { ret = <API key>(ptr); } else if (ptr >= ctl_base && ptr < (ctl_base + (mdss_res->nctl * <API key>))) { ret = <API key>(ptr); } else if (ptr >= vig_base && ptr < (vig_base + (mdss_res->nvig_pipes * <API key>))) { ret = <API key>(ptr); } else if (ptr >= rgb_base && ptr < (rgb_base + (mdss_res->nrgb_pipes * <API key>))) { ret = <API key>(ptr); } else if (ptr >= dma_base && ptr < (dma_base + (mdss_res->ndma_pipes * <API key>))) { ret = <API key>(ptr); } else if (ptr >= mixer_base && ptr < (mixer_base + (mdss_res->nmixers_intf * <API key>))) { ret = <API key>(ptr); } return ret & operation; } int <API key>(struct <API key> *cfg, u32 *copyback) { int ret = -1; void *ptr = (void *) cfg->addr; ptr = (void *)(((unsigned int) ptr) + (mdss_res->mdp_base)); if (is_valid_calib_addr(ptr, cfg->ops)) ret = 0; else return ret; mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_ON, false); if (cfg->ops & MDP_PP_OPS_READ) { cfg->data = readl_relaxed(ptr); *copyback = 1; ret = 0; } else if (cfg->ops & MDP_PP_OPS_WRITE) { writel_relaxed(cfg->data, ptr); ret = 0; } mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false); return ret; } int mdss_mdp_calib_mode(struct msm_fb_data_type *mfd, struct mdss_calib_cfg *cfg) { if (!mdss_pp_res || !mfd) return -EINVAL; mutex_lock(&mdss_pp_mutex); mfd->calib_mode = cfg->calib_mask; mutex_unlock(&mdss_pp_mutex); return 0; } int <API key>(struct <API key> *cfg, u32 *copyback) { int ret = -1, counter; uint32_t *buff = NULL, *buff_org = NULL; void *ptr; int i = 0; if (!cfg) { pr_err("Invalid buffer pointer\n"); return ret; } if (cfg->size == 0) { pr_err("Invalid buffer size\n"); return ret; } counter = cfg->size / (sizeof(uint32_t) * 2); buff_org = buff = kzalloc(cfg->size, GFP_KERNEL); if (buff == NULL) { pr_err("Config buffer allocation failed\n"); return ret; } if (copy_from_user(buff, cfg->buffer, cfg->size)) { kfree(buff); pr_err("config buffer copy failed\n"); return ret; } mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_ON, false); for (i = 0; i < counter; i++) { ptr = (void *) (((unsigned int) *buff) + mdss_res->mdp_base); if (!is_valid_calib_addr(ptr, cfg->ops)) { ret = -1; pr_err("Address validation failed or access not permitted\n"); break; } buff++; if (cfg->ops & MDP_PP_OPS_READ) *buff = readl_relaxed(ptr); else if (cfg->ops & MDP_PP_OPS_WRITE) writel_relaxed(*buff, ptr); buff++; } if (ret & MDP_PP_OPS_READ) { ret = copy_to_user(cfg->buffer, buff_org, cfg->size); *copyback = 1; } mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false); kfree(buff_org); return ret; }
# -*- coding: utf-8 -*- from __future__ import unicode_literals import json from datetime import date, datetime from dateutil.relativedelta import relativedelta import os from os import path, mkdir from shutil import rmtree import tempfile from zipfile import ZipFile, ZIP_DEFLATED import codecs import geojson from osgeo import ogr from shapely.geometry import shape, mapping from shapely.wkt import loads from pyramid.httpexceptions import HTTPForbidden, HTTPNotFound, HTTPBadRequest from pyramid.renderers import render_to_response from pyramid.response import Response, FileResponse from pyramid.view import view_config from sqlalchemy.orm import joinedload_all import sqlalchemy.sql as sql import subprocess from nextgisweb import DBSession, db from nextgisweb.feature_layer.view import PD_READ, ComplexEncoder from nextgisweb.resource import Resource, ResourceGroup, DataScope from nextgisweb.resource.model import ResourceACLRule from nextgisweb.vector_layer import VectorLayer, TableInfo from <API key>.compulink_reporting.utils import <API key> from ..compulink_admin.layers_struct_group import FOCL_LAYER_STRUCT, <API key>, <API key>,\ <API key>, <API key> from ..compulink_admin.model import SituationPlan, FoclStruct, FoclProject, <API key>, \ <API key>, FoclStructScope, Region, District, ConstructObject from ..compulink_admin.well_known_resource import <API key> from .. import compulink_admin from ..compulink_admin.view import get_region_name, get_district_name, <API key>, \ <API key>, <API key> from <API key>.compulink_reporting.model import <API key> from <API key>.compulink_site import COMP_ID from nextgisweb_log.model import LogEntry, LogLevels from <API key>.model import LookupTable from <API key>.compulink_admin.reference_books.views.<API key> import <API key> from <API key>.compulink_admin.reference_books.dgrid_viewmodels import <API key> CURR_PATH = path.dirname(__file__) ADMIN_BASE_PATH = path.dirname(path.abspath(compulink_admin.__file__)) def setup_pyramid(comp, config): config.add_route( 'compulink.site.map', '/compulink/monitoring_map', client=()).add_view(show_map) config.add_route( 'compulink.site.empty', '/compulink/empty').add_view(empty) config.add_route( 'compulink.site.json', '/compulink/resources/child').add_view(<API key>) config.add_route( 'compulink.site.focl_info', '/compulink/resources/focl_info').add_view(get_focl_info) config.add_route( 'compulink.site.focl_extent', '/compulink/resources/focl_extent').add_view(get_focl_extent) config.add_route( 'compulink.site.get_object_extent', '/compulink/resources/object_extent').add_view(get_object_extent) config.add_route( 'compulink.site.layers_by_type', '/compulink/resources/layers_by_type').add_view(get_layers_by_type) config.add_route( 'compulink.site.regions_tree', '/compulink/regions/tree').add_view(get_regions_tree) config.add_static_view( name='compulink/static', path='<API key>:compulink_site/static', cache_max_age=3600) config.add_route( 'compulink.site.export_kml', '/compulink/resources/{id:\d+}/export_kml', client=('id',)) \ .add_view(export_focl_to_kml) config.add_route( 'compulink.site.export_geojson', '/compulink/resources/{id:\d+}/export_geojson', client=('id',)) \ .add_view(<API key>) config.add_route( 'compulink.site.export_csv', '/compulink/resources/{id:\d+}/export_csv', client=('id',)) \ .add_view(export_focl_to_csv) config.add_route( 'compulink.site.get_focl_status', '/compulink/resources/{id:\d+}/focl_status', client=('id',)) \ .add_view(get_focl_status) config.add_route( 'compulink.site.set_focl_status', '/compulink/resources/{id:\d+}/set_focl_status', client=('id',)) \ .add_view(set_focl_status) config.add_route( 'compulink.site.get_dicts', '/compulink/get_dicts',) \ .add_view(get_dicts) config.add_route( 'compulink.site.get_focl_parents', '/compulink/resources/{id:\d+}/get_focl_parents', client=('id',)) \ .add_view(get_focl_parents) @view_config(renderer='json') def empty(request): return Response(json.dumps({})) @view_config(renderer='json') def <API key>(request): if request.user.keyname == 'guest': raise HTTPForbidden() parent_resource_id = request.params.get('id', None) if parent_resource_id is None: raise HTTPBadRequest('Set "id" param!') else: parent_resource_id = parent_resource_id.replace('res_', '') <API key> = parent_resource_id == ' type_filter = request.params.get('type', None) dbsession = DBSession() if <API key>: parent_resource_id = dbsession.query(Resource).filter(Resource.parent==None).all()[0].id parent_resource = dbsession.query(Resource).get(parent_resource_id) children = parent_resource.children suitable_types = [ ResourceGroup.identity, FoclProject.identity, ] if type_filter == 'vols' or not type_filter: suitable_types.append(FoclStruct.identity) if type_filter == 'sit' or not type_filter: suitable_types.append(SituationPlan.identity) if not request.user.is_administrator: allowed_res_list = <API key>(request.user) allowed_res_list = <API key>(request.user) <API key> = [] for child_resource in children: if child_resource.identity in suitable_types: # remove system folders if child_resource.identity == ResourceGroup.identity and child_resource.keyname == <API key>: continue if not request.user.is_administrator and child_resource.id not in allowed_res_list: continue is_need_checkbox = child_resource.identity in (FoclProject.identity, SituationPlan.identity, FoclStruct.identity) has_children = child_resource.identity in (ResourceGroup.identity, FoclProject.identity) <API key>.append({ 'id': 'res_' + str(child_resource.id), 'text': child_resource.display_name, 'children': has_children, 'has_children': has_children, 'icon': child_resource.identity, 'res_type': child_resource.identity, 'a_attr': {'chb': is_need_checkbox} }) # if not is_need_checkbox: # <API key>[-1]['state'] = {'disabled': True} dbsession.close() return Response(json.dumps(<API key>)) def <API key>(user): principal_ids = [user.principal_id,] for group in user.member_of: principal_ids.append(group.principal_id) # get explicit rules rules_query = DBSession.query(ResourceACLRule)\ .filter(ResourceACLRule.principal_id.in_(principal_ids))\ .filter(ResourceACLRule.scope == DataScope.identity)\ .options(joinedload_all(ResourceACLRule.resource)) allowed_res_ids = set() def <API key>(resource): # add self if resource.identity == FoclStruct.identity: if resource.has_permission(DataScope.write, user) or resource.has_permission(DataScope.read, user): allowed_res_ids.add(resource.id) elif resource.identity in [ResourceGroup.identity, FoclProject.identity]: allowed_res_ids.add(resource.id) # add childs if resource.identity in [ResourceGroup.identity, FoclProject.identity]: for child in resource.children: <API key>(child) def <API key>(resource): if resource.parent is not None: allowed_res_ids.add(resource.parent.id) <API key>(resource.parent) for rule in rules_query.all(): <API key>(rule.resource) <API key>(rule.resource) return allowed_res_ids def show_map(request): if request.user.keyname == 'guest': raise HTTPForbidden() focl_layers = <API key>() <API key> = <API key>() values = dict( show_header=True, <API key>=<API key>\ .<API key>(<API key>), focl_layers_type=focl_layers['focl'], objects_layers_type=focl_layers['objects'], real_layers_type=focl_layers['real'], <API key>=<API key> ) return render_to_response('<API key>:compulink_site/templates/monitoring_webmap/display.mako', values, request=request) def <API key>(): layer_order = len(FOCL_LAYER_STRUCT) + len(<API key>) + len(<API key>) +\ len(<API key>) <API key> = [] <API key> = path.join(ADMIN_BASE_PATH, 'layers_templates/') for vl_name in reversed(FOCL_LAYER_STRUCT): with codecs.open(path.join(<API key>, vl_name + '.json'), encoding='utf-8') as json_file: json_layer_struct = json.load(json_file, encoding='utf-8') <API key>.append({ 'text': json_layer_struct['resource']['display_name'], 'identify_text': json_layer_struct['resource']['identify_name'], 'id': vl_name, 'children': False, 'icon': vl_name, 'order': layer_order }) layer_order -= 1 <API key> = [] <API key> = path.join(ADMIN_BASE_PATH, 'layers_templates/') for vl_name in reversed(<API key>): with codecs.open(path.join(<API key>, vl_name + '.json'), encoding='utf-8') as json_file: json_layer_struct = json.load(json_file, encoding='utf-8') <API key>.append({ 'text': json_layer_struct['resource']['display_name'], 'identify_text': json_layer_struct['resource']['identify_name'], 'id': vl_name, 'children': False, 'icon': vl_name, 'order': layer_order }) layer_order -= 1 <API key> = [] <API key> = path.join(ADMIN_BASE_PATH, '<API key>/') for vl_name in reversed(<API key>): with codecs.open(path.join(<API key>, vl_name + '.json'), encoding='utf-8') as json_file: json_layer_struct = json.load(json_file, encoding='utf-8') <API key>.append({ 'text': json_layer_struct['resource']['display_name'], 'identify_text': json_layer_struct['resource']['identify_name'], 'id': vl_name, 'children': False, 'icon': vl_name, 'order': layer_order }) layer_order -= 1 return { 'focl': <API key>, 'objects': <API key>, 'real': <API key> } def <API key>(): <API key> = path.join(ADMIN_BASE_PATH, '<API key>/') layers = [] layer_order = len(<API key>) for vl_name in reversed(<API key>): with codecs.open(path.join(<API key>, vl_name + '.json'), encoding='utf-8') as json_file: json_layer_struct = json.load(json_file, encoding='utf-8') layers.append({ 'text': json_layer_struct['resource']['display_name'], 'identify_text': json_layer_struct['resource']['identify_name'], 'id': vl_name, 'children': [], 'icon': vl_name, 'order': layer_order }) layer_order -= 1 return layers @view_config(renderer='json') def get_focl_info(request): if request.user.keyname == 'guest': raise HTTPForbidden() res_ids = request.POST.getall('ids') if not res_ids: return Response('[]') now_dt = date.today() dbsession = DBSession() resources = dbsession.query(Resource).filter(Resource.id.in_(res_ids)).all() # get rows from registry focl_info_rows = { row.resource_id: row for row in dbsession.query(ConstructObject).filter(ConstructObject.resource_id.in_(res_ids)).all() } # get rows from reporting reporting_rows = { row.focl_res_id: row for row in dbsession.query(<API key>).filter(<API key>.focl_res_id.in_(res_ids)).all() } resp = [] #dicts regions = <API key>(as_dict=True) districts = <API key>(as_dict=True) statuses = <API key>(as_dict=True) for res in resources: if res.identity not in (FoclStruct.identity, SituationPlan.identity): continue # try to get data from status report if res.id in reporting_rows.keys() and res.id in focl_info_rows.keys(): report_row = reporting_rows[res.id] focl_info = focl_info_rows[res.id] resp.append( { 'id': res.id, 'display_name': focl_info.name, 'district': districts.get(focl_info.district_id, focl_info.district_id), 'region': regions.get(focl_info.region_id, focl_info.region_id), 'status': statuses.get(res.status, res.status), 'cabling_plan': focl_info.cabling_plan, 'cabling_fact': report_row.cabling_fact, 'cabling_percent': report_row.cabling_percent, 'start_build_time': focl_info.start_build_date.strftime('%d.%m.%Y') if focl_info.start_build_date else '', 'end_build_time': focl_info.end_build_date.strftime('%d.%m.%Y') if focl_info.end_build_date else '', 'start_deliver_time': focl_info.start_deliver_date.strftime('%d.%m.%Y') if focl_info.start_deliver_date else '', 'end_deliver_time': focl_info.end_deliver_date.strftime('%d.%m.%Y') if focl_info.end_deliver_date else '', 'subcontr': focl_info.subcontr_name, 'is_overdue': <API key>.overdue_status(focl_info.end_build_date, res.status), 'is_month_overdue': <API key>.<API key>(focl_info.end_build_date, res.status), 'is_focl_delivered': res.status == <API key>, 'cabling_plan_today': (focl_info.cabling_plan * (float((now_dt - focl_info.start_build_date).days)/((focl_info.end_build_date - focl_info.start_build_date).days))) if (focl_info.end_build_date and focl_info.start_build_date and focl_info.cabling_plan and (focl_info.end_build_date - focl_info.start_build_date).days !=0) else None, 'status_row': res.status, 'editable': request.user.is_administrator or res.has_permission(FoclStructScope.edit_prop, request.user) } ) # else get from registry elif res.id in focl_info_rows.keys(): focl_info = focl_info_rows[res.id] resp.append( { 'id': res.id, 'display_name': focl_info.name, 'district': districts.get(focl_info.district_id, focl_info.district_id), 'region': regions.get(focl_info.region_id, focl_info.region_id), 'status': statuses.get(res.status, res.status), 'cabling_plan': focl_info.cabling_plan, 'cabling_fact': None, 'cabling_percent': None, 'start_build_time': focl_info.start_build_date.strftime('%d.%m.%Y') if focl_info.start_build_date else '', 'end_build_time': focl_info.end_build_date.strftime('%d.%m.%Y') if focl_info.end_build_date else '', 'start_deliver_time': focl_info.start_deliver_date.strftime('%d.%m.%Y') if focl_info.start_deliver_date else '', 'end_deliver_time': focl_info.end_deliver_date.strftime('%d.%m.%Y') if focl_info.end_deliver_date else '', 'subcontr': focl_info.subcontr_name, 'is_overdue': <API key>.overdue_status(focl_info.end_build_date, res.status), 'is_month_overdue': <API key>.<API key>(focl_info.end_build_date, res.status), 'is_focl_delivered': res.status == <API key>, 'cabling_plan_today': (focl_info.cabling_plan * (float((now_dt - focl_info.start_build_date).days)/((focl_info.end_build_date - focl_info.start_build_date).days))) if (focl_info.end_build_date and focl_info.start_build_date and focl_info.cabling_plan and (focl_info.end_build_date - focl_info.start_build_date).days !=0) else None, 'status_row': res.status, 'editable': request.user.is_administrator or res.has_permission(FoclStructScope.edit_prop, request.user) } ) else: # else get from resource resp.append( { 'id': res.id, 'display_name': res.display_name, 'district': districts.get(res.district, res.district), 'region': regions.get(res.region, res.region), 'status': statuses.get(res.status, res.status), 'cabling_plan': None, 'cabling_fact': None, 'cabling_percent': None, 'start_build_time': None, 'end_build_time': None, 'start_deliver_time': None, 'end_deliver_time': None, 'subcontr': None, 'is_overdue': False, 'is_month_overdue': False, 'is_focl_delivered': res.status == <API key>, 'cabling_plan_today': None, 'status_row': res.status, 'editable': request.user.is_administrator or res.has_permission(FoclStructScope.edit_prop, request.user) } ) dbsession.close() return Response(json.dumps(resp)) @view_config(renderer='json') def get_focl_parents(request): if request.user.keyname == 'guest': raise HTTPForbidden() res_id = request.matchdict['id'] response = [] try: dbsession = DBSession() focl_resource = dbsession.query(FoclStruct).get(res_id) except: raise HTTPNotFound() if not focl_resource: raise HTTPNotFound() while focl_resource: response.append(focl_resource.id) focl_resource = focl_resource.parent response.reverse() return Response(json.dumps(response[:-1])) def extent_union(extent, new_extent): return [ extent[0] if extent[0] < new_extent[0] else new_extent[0], extent[1] if extent[1] < new_extent[1] else new_extent[1], extent[2] if extent[2] > new_extent[2] else new_extent[2], extent[3] if extent[3] > new_extent[3] else new_extent[3], ] def extent_buff(extent, buff_size): if extent: return [ extent[0] - buff_size, extent[1] - buff_size, extent[2] + buff_size, extent[3] + buff_size, ] return None @view_config(renderer='json') def get_focl_extent(request): if request.user.keyname == 'guest': raise HTTPForbidden() res_id = request.params.get('id', None) if res_id is None: return Response('[]') resp = {'extent': <API key>(res_id)} return Response(json.dumps(resp)) def <API key>(resource_id): session = DBSession() resource = session.query(Resource).filter(Resource.id == resource_id).first() extent = None for res in resource.children: if res.identity != VectorLayer.identity or (res.keyname and res.keyname.startswith('real_')): continue table_info = TableInfo.from_layer(res) table_info.setup_metadata(tablename=res._tablename) columns = [db.func.st_astext(db.func.st_extent(db.text('geom')).label('box'))] query = sql.select(columns=columns, from_obj=table_info.table) extent_str = session.connection().scalar(query) if extent_str: if not extent: extent = loads(extent_str).bounds else: new_extent = loads(extent_str).bounds extent = extent_union(extent, new_extent) session.close() return extent_buff(extent, 2000) @view_config(renderer='json') def get_object_extent(request): if request.user.keyname == 'guest': raise HTTPForbidden() resource_id = request.params.get('resource_id', None) object_type = request.params.get('object_type', None) object_num = request.params.get('object_num', None) if resource_id is None: return Response('[]') if None in (object_num, object_type): resp = {'extent': <API key>(resource_id)} return Response(json.dumps(resp)) extent = <API key>(resource_id, object_type, object_num) if not extent: extent = <API key>(resource_id) resp = {'extent': extent} return Response(json.dumps(resp)) def <API key>(resource_id, object_type, object_num): extent = [] session = DBSession() resource = session.query(Resource).filter(Resource.id == resource_id).first() if not resource: return extent layer_type = 'actual_real_' + object_type layer = None for res in resource.children: if get_layer_type(res) == layer_type: layer = res break if not layer: return extent query = layer.feature_query() query.box() query.filter_by(id=object_num) query.limit(1) obj = None for f in query(): obj = f if not obj: return extent return obj.box.bounds def get_layer_type(layer): if layer.keyname and '_' in layer.keyname: return '_'.join(layer.keyname.rsplit('_')[:-1]) else: return None @view_config(renderer='json') def get_layers_by_type(request): if request.user.keyname == 'guest': raise HTTPForbidden() # TODO: optimize this!!! group_res_ids = request.POST.getall('resources') layer_types = request.POST.getall('types') if not group_res_ids or not layer_types: return Response("[]") layer_types.sort(reverse=True) resp_list = [] dbsession = DBSession() group_resources = dbsession.query(Resource).options(joinedload_all('children.children')).filter(Resource.id.in_(group_res_ids)).all() for group_res in group_resources: for child_res in group_res.children: if child_res.identity != VectorLayer.identity or not child_res.keyname: continue lyr_type = <API key>(layer_types, child_res.keyname) if not lyr_type: continue style_resorces = child_res.children if not style_resorces: continue resp_list.append({ 'vector_id': child_res.id, 'style_id': style_resorces[0].id, 'res_id': group_res.id, 'type': lyr_type, 'res_type': group_res.identity }) dbsession.close() return Response(json.dumps(resp_list)) def <API key>(layers_types, name): for layer_type in layers_types: if name.startswith(layer_type): if '_point' in layer_type and '_point' not in name: continue if '_point' not in layer_type and '_point' in name: continue return layer_type return None def get_all_dicts(): dbsession = DBSession() dicts_resources = dbsession.query(LookupTable).all() dicts = {} for dict_res in dicts_resources: dicts[dict_res.keyname] = dict_res.val dbsession.close() return dicts @view_config(renderer='json') def get_dicts(request): return Response(json.dumps(get_all_dicts())) def export_focl_to_kml(request): return export_focl_struct(request, 'kml') def <API key>(request): return export_focl_struct(request, 'geojson') def export_focl_to_csv(request): return export_focl_struct(request, 'csv') def export_focl_struct(request, export_type): res_id = request.matchdict['id'] dbsession = DBSession() try: focl_resource = dbsession.query(FoclStruct).get(res_id) except: raise HTTPNotFound() if not focl_resource.has_permission(DataScope.read, request.user): raise HTTPForbidden() LogEntry.info('Export resource %s to %s' % (res_id, export_type), component=COMP_ID) #create temporary dir zip_dir = tempfile.mkdtemp() # save layers to geojson (FROM FEATURE_LAYER) for layer in focl_resource.children: if layer.identity == VectorLayer.identity and layer.feature_query()().total_count > 0: json_path = path.join(zip_dir, '%s.%s' % (layer.display_name, 'json')) <API key>(layer, json_path, single_geom=export_type == 'csv') if export_type == 'kml': kml_path = path.join(zip_dir, '%s.%s' % (layer.display_name, 'kml')) _json_to_kml(json_path, kml_path) # remove json os.remove(json_path.encode('utf-8')) if export_type == 'csv': csv_path = path.join(zip_dir, '%s.%s' % (layer.display_name, 'csv')) _json_to_csv(json_path, csv_path) # remove json os.remove(json_path.encode('utf-8')) with tempfile.NamedTemporaryFile(delete=True) as temp_file: # write archive zip_file = ZipFile(temp_file, mode="w", compression=ZIP_DEFLATED) zip_subpath = focl_resource.display_name + '/' for file_name in os.listdir(zip_dir): src_file = path.join(zip_dir, file_name) zip_file.write(src_file, (zip_subpath+unicode(file_name, 'utf-8')).encode('cp866', errors='ignore')) zip_file.close() # remove temporary dir rmtree(zip_dir) # send temp_file.seek(0, 0) response = FileResponse( path.abspath(temp_file.name), content_type=bytes('application/zip'), request=request ) disp_name = focl_resource.display_name for ch in '\\/:*?"<>|': disp_name = disp_name.replace(ch, '') response.content_disposition = (u'attachment; filename="%s [%s].zip"' % (disp_name, export_type)).encode('utf-8') return response def <API key>(vector_resource, file_path, single_geom=False): class CRSProxy(object): def __init__(self, query): self.query = query @property def __geo_interface__(self): result = self.query.__geo_interface__ result['crs'] = dict(type='name', properties=dict( name='EPSG:3857')) return result query = vector_resource.feature_query() query.geom(single_part=single_geom) result = CRSProxy(query()) gj = geojson.dumps(result, ensure_ascii=False, cls=ComplexEncoder) with codecs.open(file_path.encode('utf-8'), 'w', encoding='utf-8') as f: f.write(gj) def _json_to_kml(in_file_path, out_file_path): subprocess.check_call(['ogr2ogr', '-f', 'KML', out_file_path.encode('utf-8'), in_file_path.encode('utf-8')]) def _json_to_csv(in_file_path, out_file_path): subprocess.check_call(['ogr2ogr', '-f', 'CSV', out_file_path.encode('utf-8'), in_file_path.encode('utf-8'), '-lco', 'GEOMETRY=AS_XY', '-s_srs', 'EPSG:3857', '-t_srs', 'EPSG:4326']) @view_config(renderer='json') def get_focl_status(request): res_id = request.matchdict['id'] dbsession = DBSession() try: focl_resource = dbsession.query(FoclStruct).get(res_id) except: raise HTTPNotFound() if not focl_resource: raise HTTPNotFound() if not (focl_resource.has_permission(DataScope.write, request.user) or focl_resource.has_permission(DataScope.read, request.user)): raise HTTPForbidden() resp = { 'statuses': <API key>(), 'focl_status': focl_resource.status } return Response(json.dumps(resp)) @view_config(renderer='json') def set_focl_status(request): res_id = request.matchdict['id'] dbsession = DBSession() new_status = request.params.get('status', None) if new_status is None or new_status not in <API key>(as_dict=True).keys(): raise HTTPBadRequest('Set right status!') # update resource try: focl_resource = dbsession.query(FoclStruct).get(res_id) except: raise HTTPNotFound() if not focl_resource: raise HTTPNotFound() if not focl_resource.has_permission(DataScope.write, request.user): raise HTTPForbidden() focl_resource.status = new_status focl_resource.persist() # update reports try: report_line = dbsession.query(<API key>).filter(<API key>.focl_res_id == res_id).one() except: report_line = None if report_line: now_dt = date.today() report_line.status = new_status if report_line.end_build_time and \ now_dt > report_line.end_build_time.date() and \ report_line.status not in [<API key>, <API key>]: report_line.is_overdue = True report_line.is_month_overdue = now_dt - relativedelta(months=1) > report_line.end_build_time.date() else: report_line.is_overdue = False report_line.is_month_overdue = False report_line.persist() return Response(json.dumps({'status': 'ok'})) @view_config(renderer='json') def get_regions_tree(request): if request.user.keyname == 'guest': raise HTTPForbidden() parent_region_id = request.params.get('id', None) if parent_region_id is None: raise HTTPBadRequest('Set "id" param!') else: parent_region_id = parent_region_id.replace('reg_', '') <API key> = parent_region_id == ' dbsession = DBSession() is_region = False if <API key>: is_region = True children = dbsession.query(Region).order_by(Region.name).all() else: children = dbsession.query(District)\ .filter(District.region_id == parent_region_id)\ .order_by(District.name)\ .all() child_json = [] for child in children: has_children = type(child) is Region is_need_checkbox = False child_json.append({ 'id': ('reg_' if is_region else 'distr_') + str(child.id), 'text': child.name, 'children': has_children, 'has_children': has_children, # 'icon': child_resource.identity, # 'res_type': child_resource.identity, 'a_attr': {'chb': is_need_checkbox} }) dbsession.close() return Response(json.dumps(child_json))
/** @file * VBoxGuestR3Lib - Ring-3 Support Library for VirtualBox guest additions, * implements the minimum of runtime functions needed for * XFree86 driver code. */ #include <iprt/assert.h> #include <iprt/log.h> #include <iprt/mem.h> #if defined(VBOX_VBGLR3_XFREE86) extern "C" { # define XFree86LOADER # include <xf86_ansic.h> # undef size_t } #else # include <stdarg.h> # include <stdlib.h> # define xalloc malloc # define xfree free extern "C" void ErrorF(const char *f, ...); #endif RTDECL(void) RTAssertMsg1Weak(const char *pszExpr, unsigned uLine, const char *pszFile, const char *pszFunction) { ErrorF("Assertion failed! Expression: %s at %s in\n", pszExpr, pszFunction); ErrorF("%s:%u\n", pszFile, uLine); } RTDECL(void) RTAssertMsg2Weak(const char *pszFormat, ...) { NOREF(pszFormat); } RTDECL(bool) RTAssertShouldPanic(void) { return false; } RTDECL(PRTLOGGER) <API key>(void) { return NULL; } RTDECL(void) RTLogLoggerEx(PRTLOGGER, unsigned, unsigned, const char *pszFormat, ...) { NOREF(pszFormat); } RTDECL(void *) RTMemTmpAllocTag(size_t cb, const char *pszTag) { NOREF(pszTag); return xalloc(cb); } RTDECL(void) RTMemTmpFree(void *pv) { xfree(pv); }
#pragma once #include "../Raytracer.h" #include "../Color/RayColor.h" #include "../Traversal/Intersection.h" #include "../../Common/Math/Matrix4.hpp" namespace NFE { namespace RT { struct <API key> { RayColor baseColor; RayColor emissionColor; float roughness; float roughnessAnisotropy; float metalness; float IoR; }; struct ShadingData { // geometry data IntersectionData intersection; // incoming ray data Math::Vec4f <API key>; <API key> materialParams; }; } // namespace RT } // namespace NFE
/* <API key>: LGPL-2.1-or-later */ #include <errno.h> #include <fcntl.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <linux/fs.h> #include "chattr-util.h" #include "fd-util.h" #include "macro.h" int chattr_full(const char *path, int fd, unsigned value, unsigned mask, unsigned *ret_previous, unsigned *ret_final, bool fallback) { _cleanup_close_ int fd_will_close = -1; unsigned old_attr, new_attr; struct stat st; assert(path || fd >= 0); if (fd < 0) { fd = fd_will_close = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW); if (fd < 0) return -errno; } if (fstat(fd, &st) < 0) return -errno; /* Explicitly check whether this is a regular file or directory. If it is anything else (such * as a device node or fifo), then the ioctl will not hit the file systems but possibly * drivers, where the ioctl might have different effects. Notably, DRM is using the same * ioctl() number. */ if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode)) return -ENOTTY; if (mask == 0 && !ret_previous && !ret_final) return 0; if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0) return -errno; new_attr = (old_attr & ~mask) | (value & mask); if (new_attr == old_attr) { if (ret_previous) *ret_previous = old_attr; if (ret_final) *ret_final = old_attr; return 0; } if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) >= 0) { if (ret_previous) *ret_previous = old_attr; if (ret_final) *ret_final = new_attr; return 1; } if (errno != EINVAL || !fallback) return -errno; unsigned current_attr = old_attr; for (unsigned i = 0; i < sizeof(unsigned) * 8; i++) { unsigned new_one, mask_one = 1u << i; if (!FLAGS_SET(mask, mask_one)) continue; new_one = UPDATE_FLAG(current_attr, mask_one, FLAGS_SET(value, mask_one)); if (new_one == current_attr) continue; if (ioctl(fd, FS_IOC_SETFLAGS, &new_one) < 0) { if (errno != EINVAL) return -errno; continue; } if (ioctl(fd, FS_IOC_GETFLAGS, &current_attr) < 0) return -errno; } if (ret_previous) *ret_previous = old_attr; if (ret_final) *ret_final = current_attr; return current_attr == new_attr ? 1 : -ENOANO; /* -ENOANO indicates that some attributes cannot be set. */ } #if 0 /// UNNEEDED by elogind int read_attr_fd(int fd, unsigned *ret) { struct stat st; assert(fd >= 0); if (fstat(fd, &st) < 0) return -errno; if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode)) return -ENOTTY; if (ioctl(fd, FS_IOC_GETFLAGS, ret) < 0) return -errno; return 0; } int read_attr_path(const char *p, unsigned *ret) { _cleanup_close_ int fd = -1; assert(p); assert(ret); fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW); if (fd < 0) return -errno; return read_attr_fd(fd, ret); } #endif
<?php /** * The public-facing functionality of the plugin. * * Defines the plugin name, version, and two examples hooks for how to * enqueue the admin-specific stylesheet and JavaScript. * * @package Simple_Google_Map * @subpackage Simple_Google_Map/public * @author Taylor Gorman <taylor@clarknikdelpowell.com>, Glenn Welser <glenn@clarknikdelpowell.com> */ class <API key> { /** * The ID of this plugin. * * @since 3.0.0 * @access private * @var string $plugin_name The ID of this plugin. */ private $plugin_name; /** * The path of this plugin. * * @since 3.0.0 * @access protected * @var string $plugin_path The string path of this plugin. */ protected $plugin_path; /** * The version of this plugin. * * @since 3.0.0 * @access private * @var string $version The current version of this plugin. */ private $version; /** * Initialize the class and set its properties. * * @since 3.0.0 * * @param string $plugin_name The name of the plugin. * @param string $version The version of this plugin. */ public function __construct( $plugin_name, $version ) { $this->plugin_name = $plugin_name; $this->version = $version; } /** * Enqueue scripts * * @since 3.1.0 */ public function enqueue_scripts() { global $post; if ( has_shortcode( $post->post_content, 'SGM' ) || is_active_widget( false, false, '<API key>', true ) ) { $source = 'https://maps.googleapis.com/maps/api/js'; $api_key = $this->get_api_key(); if ( $api_key ) { $source .= '?key=' . $api_key; } wp_enqueue_script( 'google-maps', $source ); } } /** * Output CSS into header * * @since 3.0.0 */ public function output_css() { $sgm_options = get_option( 'SGMoptions' ); if ( isset( $sgm_options['nostyle'] ) ) { return; } echo "<!-- styles for Simple Google Map -->\n<style type='text/css'>\n"; echo get_option( 'SGMcss' ); echo "\n</style>\n<!-- end styles for Simple Google Map -->\n"; } /** * Output CSS into header * * @since 3.0.0 */ public function map( $atts ) { $sgm_options = get_option( 'SGMoptions' ); // get options defined in admin page $sgm_options = wp_parse_args( $sgm_options, Simple_Google_Map::$default_options ); $lat = isset( $atts['lat'] ) ? $atts['lat'] : '0'; $lng = isset( $atts['lng'] ) ? $atts['lng'] : '0'; $zoom = isset( $atts['zoom'] ) ? $atts['zoom'] : $sgm_options['zoom']; $type = isset( $atts['type'] ) ? strtoupper( $atts['type'] ) : $sgm_options['type']; $content = isset( $atts['content'] ) ? $atts['content'] : $sgm_options['content']; $directions_to = isset( $atts['directionsto'] ) ? $atts['directionsto'] : ''; $auto_open = isset( $atts['autoopen'] ) ? $atts['autoopen'] : false; $icon = isset( $atts['icon'] ) ? esc_url( $atts['icon'], array( 'http', 'https', ) ) : $sgm_options['icon']; $content = Simple_Google_Map::strip_last_chars( <API key>( $content ), array( '<br>', '<br/>', '<br />', ) ); $directions_form = ''; if ( $directions_to ) { $directions_form = '<form method="get" action="//maps.google.com/maps"><input type="hidden" name="daddr" value="' . $directions_to . '" /><input type="text" class="text" name="saddr" /><input type="submit" class="submit" value="Directions" /></form>'; } $marker = "var marker = new google.maps.Marker({ position: latlng, map: map, title: '',"; if ( $icon ) { $icon = "var image = { url: '$icon', };"; $marker .= "\n" . 'icon: image,' . "\n"; } $marker .= '});'; $infowindow_arr = array( $content, $directions_form ); $infowindow_content = implode( '<br>', array_filter( $infowindow_arr ) ); $infowindow_content = str_replace( "\r", "", $infowindow_content ); $infowindow_content = str_replace( "\n", "", $infowindow_content ); $infowindow_open = $auto_open ? 'infowindow.open(map,marker);' . "\n" : ''; $map = '<script type="text/javascript">'; $map .= "function makeMap() { var latlng = new google.maps.LatLng($lat, $lng); var myOptions = { zoom: $zoom, center: latlng, mapTypeControl: true, <API key>: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}, navigationControl: true, <API key>: {style: google.maps.<API key>.SMALL}, mapTypeId: google.maps.MapTypeId.$type }; var map = new google.maps.Map(document.getElementById('SGM'), myOptions); var contentstring = '<div class=\"infoWindow\">$infowindow_content</div>'; var infowindow = new google.maps.InfoWindow({ content: contentstring }); $icon $marker google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker); }); $infowindow_open }; window.onload = makeMap;"; $map .= '</script>'; $map .= '<div id="SGM"></div>'; return $map; } /** * Get the Google Maps API Key * * @since 4.0.0 */ public function get_api_key() { $sgm_options = get_option( 'SGMoptions' ); $sgm_options = wp_parse_args( $sgm_options, Simple_Google_Map::$default_options ); $api_key = $sgm_options['api_key']; return $api_key; } }
#include <stdio.h> #include "basictyp.h" #include "common.h" #include "devicerequest.h" #include "usb.h" #include "HAL4D13.h" #include "chap_9.h" #include "D13BUS.h" #include "iso.h" extern IO_REQUEST idata ioRequest; extern D13FLAGS bD13flags; extern <API key> <API key>;; extern CONTROL_XFER ControlData; /* printf("1:%X 2:%X 34:%X 56:%X 78:%X\n", ControlData.DeviceRequest.bmRequestType, ControlData.DeviceRequest.bRequest, ControlData.DeviceRequest.wValue, ControlData.DeviceRequest.wIndex, ControlData.DeviceRequest.wLength); */ if( j == sizeof(DEVICE_REQUEST) ) // if( <API key>(<API key>, (UCHAR *)(&(ControlData.DeviceRequest)), sizeof(ControlData.DeviceRequest)) // == sizeof(DEVICE_REQUEST) ) { //printf("ControlData.DeviceRequest_size:%d\n",sizeof(ControlData.DeviceRequest)); //printf("ControlData.DeviceRequest.bmRequestType:0x%X\n",ControlData.DeviceRequest.bmRequestType); //1BYTE //printf("ControlData.DeviceRequest.bRequest:0x%X\n",ControlData.DeviceRequest.bRequest);//1BYTE //printf("ControlData.DeviceRequest.wValue:0x%X\n",ControlData.DeviceRequest.wValue); //2BYTE //printf("ControlData.DeviceRequest.wIndex:0x%X\n",ControlData.DeviceRequest.wIndex); //2BYTE //printf("ControlData.DeviceRequest.wLength:0x%X\n",ControlData.DeviceRequest.wLength);//2BYTE bD13flags.bits.At_IRQL1 = 0; LowerIRQL(); ControlData.wLength = ControlData.DeviceRequest.wLength; ControlData.wCount = 0; if (ControlData.DeviceRequest.bmRequestType & (UCHAR)<API key>) { /* get command */ RaiseIRQL(); ML_AcknowledgeSETUP(); if((ControlData.DeviceRequest.bRequest == 0) & (ControlData.DeviceRequest.bmRequestType == 0xc0)) bD13flags.bits.DCP_state = <API key>; else bD13flags.bits.DCP_state = <API key>; LowerIRQL(); } else { /* set command */ if (ControlData.DeviceRequest.wLength == 0) { /* Set command without Data stage*/ RaiseIRQL(); ML_AcknowledgeSETUP(); bD13flags.bits.DCP_state = <API key>; LowerIRQL(); } else { /* // Set command with Data stage // get Data Buffer */ if(ControlData.DeviceRequest.wLength <= <API key>) { /* set command with OUT token */ RaiseIRQL(); bD13flags.bits.DCP_state = USBFSM4DCP_DATAOUT; LowerIRQL(); ML_AcknowledgeSETUP(); } else { RaiseIRQL(); ML_AcknowledgeSETUP(); <API key>(); bD13flags.bits.DCP_state = USBFSM4DCP_STALL; printf("bD13flags.bits.DCP_state = x%hx\n Unknow set up command\n", bD13flags.bits.DCP_state); LowerIRQL(); } } } } else { printf("wrong setup command\n"); bD13flags.bits.At_IRQL1 = 0; LowerIRQL(); Chap9_StallEP0(); } // printf("To_Ha_end\n"); } void <API key>(void) { UCHAR type, req; type = ControlData.DeviceRequest.bmRequestType & <API key>; req = ControlData.DeviceRequest.bRequest & USB_REQUEST_MASK; //if (bD13flags.bits.verbose==1) // printf("type = 0x%02x, req = 0x%02x\n", type, req); // help_devreq(type, req); /* print out device request */ if ((type == <API key>) && (req < <API key>)) { (*<API key>[req])(); } else if ((type == USB_CLASS_REQUEST) && (req < MAX_CLASS_REQUEST)) (*ClassDeviceRequest[req])(); else if ((type == USB_VENDOR_REQUEST) && (req < MAX_VENDOR_REQUEST)) (*VendorDeviceRequest[req])(); else{ Chap9_StallEP0(); } } void help_devreq(UCHAR type, UCHAR req) { UCHAR typ = type; typ >>= 5; if(type == <API key>) { printf("Request Type = %s, Request = %s.\n", <API key>[typ], <API key>[req]); } else if(type == USB_CLASS_REQUEST) { printf("Request Type = %s, Request = %s.\n", <API key>[typ], <API key>[req]); } else { if(bD13flags.bits.verbose) printf("Request Type = %s, bRequest = 0x%x.\n", <API key>[typ], req); } } void disconnect_USB(void) { printf("disconnect\n"); <API key>( <API key> |<API key> |<API key> ); Hal4D13_SetMode( D13REG_MODE_INT_EN ); } void connect_USB(void) { RaiseIRQL(); printf("connect_USB\n"); bD13flags.value = 0; /* reset event flags*/ bD13flags.bits.DCP_state = USBFSM4DCP_IDLE; config_endpoint(); LowerIRQL(); Hal4D13_SetMode( <API key>| D13REG_MODE_DMA16 | // <API key> | //| D13REG_MODE_DBG D13REG_MODE_INT_EN //| D13REG_MODE_SUSPND ); } void config_endpoint(void) { /*Control Endpoint*/ printf("CONFIG\n"); <API key>(<API key>|<API key>,<API key>); <API key>(<API key>|D13REG_EPCNFG_IN_EN|<API key>,<API key>); /*Control Endpoint*/ /*port1 is OUT*/ <API key>( <API key>| //<API key>| <API key>, EPINDEX4EP01 ); /*port2 is IN*/ <API key>( <API key>| // <API key>| D13REG_EPCNFG_IN_EN| <API key>, EPINDEX4EP02 ); /*DISABLED*/ /*Bulk Enpoints Double Buffered*/ <API key>(/*<API key>|*/<API key>|<API key>,EPINDEX4EP03); <API key>(/*<API key>|*/<API key>|D13REG_EPCNFG_IN_EN|<API key>,EPINDEX4EP04); /*Bulk Enpoints Double Buffered*/ /*Isochronous Endpoints*/ <API key>(/*<API key>|*/<API key>|<API key>|<API key>,EPINDEX4EP05); <API key>(/*<API key>|*/<API key>|<API key>|<API key>|D13REG_EPCNFG_IN_EN,EPINDEX4EP06); /*Isochronous Endpoints*/ /*DISABLED*/ <API key>(/*<API key>|*/<API key>|<API key>|<API key>,EPINDEX4EP07); <API key>(/*<API key>|*/D13REG_EPCNFG_IN_EN|<API key>|<API key>|<API key>,EPINDEX4EP08); <API key>(/*<API key>|*/<API key>|<API key>|<API key>,EPINDEX4EP09); <API key>(/*<API key>|*/D13REG_EPCNFG_IN_EN|<API key>|<API key>|<API key>,EPINDEX4EP0A); <API key>(/*<API key>|*/<API key>|<API key>|<API key>,EPINDEX4EP0B); <API key>(/*<API key>|*/D13REG_EPCNFG_IN_EN|<API key>|<API key>|<API key>,EPINDEX4EP0C); <API key>(/*<API key>|*/<API key>|<API key>|<API key>,EPINDEX4EP0D); <API key>(/*<API key>|*/D13REG_EPCNFG_IN_EN|<API key>|<API key>|<API key>,EPINDEX4EP0E); /*DISABLED*/ /*Set interrupt configuration*/ <API key>( <API key> |D13REG_INTSRC_EP0IN |D13REG_INTSRC_EP01 |D13REG_INTSRC_EP02 // |D13REG_INTSRC_EP03 // |D13REG_INTSRC_EP04 // |D13REG_INTSRC_EP05 // |D13REG_INTSRC_EP06 |<API key> |<API key> |<API key> ); /*Set Hardware Configuration*/ <API key>(<API key> |<API key> |<API key> // |<API key> ); } void reconnect_USB(void) { disconnect_USB(); connect_USB(); } void suspend_change(void) { printf("SUSPEND CHANGE \n"); // disconnect_USB(); // <API key>(); } void ML_AcknowledgeSETUP(void) { if( <API key>() || ControlData.Abort) { return; } <API key>(); Hal4D13_ClearBuffer(<API key>); } void ML_Reserved(void) { Hal4D13_ClearBuffer(<API key>); } unsigned short CHECK_CHIP_ID(void) { unsigned short CHIP_ID; unsigned char LOW_ID, HIGH_ID; CHIP_ID= Hal4D13_ReadChipID(); LOW_ID = (unsigned char)CHIP_ID; HIGH_ID = (unsigned char)(CHIP_ID >> 8) ; switch(HIGH_ID) { case 0x61 : { printf(" CHIP ID =0x%04x\n\n",CHIP_ID); CHIP_ID =0x1161; return CHIP_ID; break; } case 0x36 : { printf(" CHIP ID =0x%04x\n\n",CHIP_ID); CHIP_ID = 0x1362; return CHIP_ID; break; } default : { printf(" UNKNOWN CHIP ID =0x%04x\n\n",CHIP_ID); return CHIP_ID; break; } } }
#ifndef <API key> #define <API key> #include <cassert> #include <cerrno> #include <cstring> #include <fcntl.h> #include <stdexcept> #include <string> #include <vector> namespace osmium { namespace index { namespace detail { template <typename T> inline T* create_map_with_fd(const std::vector<std::string>& config) { if (config.size() == 1) { return new T{}; } assert(config.size() > 1); const std::string& filename = config[1]; const int fd = ::open(filename.c_str(), O_CREAT | O_RDWR, 0644); // NOLINT(<API key>) if (fd == -1) { throw std::runtime_error{std::string{"can't open file '"} + filename + "': " + std::strerror(errno)}; } return new T{fd}; } } // namespace detail } // namespace index } // namespace osmium #endif // <API key>
<?php function processRequest(&$db) { if (getDbName() == '') { echo view('invalid_request'); return; } if ($db->queryTableStatus()) createSimpleGrid($db, __('Database summary').': ['.htmlspecialchars(getDbName()).']'); } ?>
#ifndef EXPORT_SYMTAB # define EXPORT_SYMTAB #endif #define DEBUG_SUBSYSTEM S_MDS #include <linux/module.h> #include <lustre_ver.h> #include "mdd_internal.h" void mdd_write_lock(const struct lu_env *env, struct mdd_object *obj, enum mdd_object_role role) { struct dt_object *next = mdd_object_child(obj); next->do_ops->do_write_lock(env, next, role); } void mdd_read_lock(const struct lu_env *env, struct mdd_object *obj, enum mdd_object_role role) { struct dt_object *next = mdd_object_child(obj); next->do_ops->do_read_lock(env, next, role); } void mdd_write_unlock(const struct lu_env *env, struct mdd_object *obj) { struct dt_object *next = mdd_object_child(obj); next->do_ops->do_write_unlock(env, next); } void mdd_read_unlock(const struct lu_env *env, struct mdd_object *obj) { struct dt_object *next = mdd_object_child(obj); next->do_ops->do_read_unlock(env, next); } int mdd_write_locked(const struct lu_env *env, struct mdd_object *obj) { struct dt_object *next = mdd_object_child(obj); return next->do_ops->do_write_locked(env, next); } unsigned long mdd_name2hash(const char *name) { return full_name_hash((unsigned char*)name, strlen(name)); } /* Methods for parallel directory locking */ #if <API key> static void *pdo_handle = (void *)0xbabecafe; void mdd_pdlock_init(struct mdd_object *obj) { } void *mdd_pdo_write_lock(const struct lu_env *env, struct mdd_object *obj, const char *name, enum mdd_object_role role) { return pdo_handle; } void *mdd_pdo_read_lock(const struct lu_env *env, struct mdd_object *obj, const char *name, enum mdd_object_role role) { return pdo_handle; } void <API key>(const struct lu_env *env, struct mdd_object *obj, void *dlh) { LASSERT(dlh == pdo_handle); } void mdd_pdo_read_unlock(const struct lu_env *env, struct mdd_object *obj, void *dlh) { LASSERT(dlh == pdo_handle); } #else /* !<API key> */ #ifdef CONFIG_LOCKDEP static <API key> mdd_pdirop_key; #define RETIP ((unsigned long)<API key>(0)) static void mdd_lockdep_init(struct mdd_object *obj) { <API key>(obj, &mdd_pdirop_key, "pdir"); } static void <API key>(struct mdd_object *obj, enum mdd_object_role role) { #ifdef <API key> lock_map_acquire(&obj->dep_map); #else lock_acquire(&obj->dep_map, role, 0, 1, 2, RETIP); #endif } static void <API key>(struct mdd_object *obj) { #ifdef <API key> lock_map_release(&obj->dep_map); #else lock_release(&obj->dep_map, 0, RETIP); #endif } #else /* !CONFIG_LOCKDEP */ static void mdd_lockdep_init(struct mdd_object *obj) {} static void <API key>(struct mdd_object *obj, enum mdd_object_role role) {} static void <API key>(struct mdd_object *obj) {} #endif /* !CONFIG_LOCKDEP */ void mdd_pdlock_init(struct mdd_object *obj) { dynlock_init(&obj->mod_pdlock); mdd_lockdep_init(obj); } void *mdd_pdo_write_lock(const struct lu_env *env, struct mdd_object *obj, const char *name, enum mdd_object_role role) { struct dynlock_handle *handle; unsigned long value = mdd_name2hash(name); handle = dynlock_lock(&obj->mod_pdlock, value, DLT_WRITE, GFP_NOFS); if (handle != NULL) <API key>(obj, role); return handle; } void *mdd_pdo_read_lock(const struct lu_env *env, struct mdd_object *obj, const char *name, enum mdd_object_role role) { struct dynlock_handle *handle; unsigned long value = mdd_name2hash(name); handle = dynlock_lock(&obj->mod_pdlock, value, DLT_READ, GFP_NOFS); if (handle != NULL) <API key>(obj, role); return handle; } void <API key>(const struct lu_env *env, struct mdd_object *obj, void *dlh) { <API key>(obj); return dynlock_unlock(&obj->mod_pdlock, dlh); } void mdd_pdo_read_unlock(const struct lu_env *env, struct mdd_object *obj, void *dlh) { <API key>(obj); return dynlock_unlock(&obj->mod_pdlock, dlh); } #endif /* <API key> */
<?php /** * This file has been @generated by a phing task by {@link <API key>}. * See [README.md](README.md#generating-data) for more information. * * Pull requests changing data in these files will not be accepted. See the * [FAQ in the README](README.md#<API key>] on how to make * metadata changes. * * Do not modify this file directly! */ return array ( 'generalDesc' => array ( '<API key>' => '[1-689]\\d{5}', '<API key>' => '\\d{6}', 'PossibleLength' => array ( 0 => 6, ), '<API key>' => array ( ), ), 'fixedLine' => array ( '<API key>' => '(?:19|3[1-6]|6[14689]|8[14-79]|9\\d)\\d{4}', '<API key>' => '\\d{6}', 'ExampleNumber' => '321000', 'PossibleLength' => array ( ), '<API key>' => array ( ), ), 'mobile' => array ( '<API key>' => '[245][2-9]\\d{4}', '<API key>' => '\\d{6}', 'ExampleNumber' => '221234', 'PossibleLength' => array ( ), '<API key>' => array ( ), ), 'tollFree' => array ( '<API key>' => '80\\d{4}', '<API key>' => '\\d{6}', 'ExampleNumber' => '801234', 'PossibleLength' => array ( ), '<API key>' => array ( ), ), 'premiumRate' => array ( '<API key>' => 'NA', '<API key>' => 'NA', 'PossibleLength' => array ( 0 => -1, ), '<API key>' => array ( ), ), 'sharedCost' => array ( '<API key>' => 'NA', '<API key>' => 'NA', 'PossibleLength' => array ( 0 => -1, ), '<API key>' => array ( ), ), 'personalNumber' => array ( '<API key>' => 'NA', '<API key>' => 'NA', 'PossibleLength' => array ( 0 => -1, ), '<API key>' => array ( ), ), 'voip' => array ( '<API key>' => '3[89]\\d{4}', '<API key>' => '\\d{6}', 'ExampleNumber' => '381234', 'PossibleLength' => array ( ), '<API key>' => array ( ), ), 'pager' => array ( '<API key>' => 'NA', '<API key>' => 'NA', 'PossibleLength' => array ( 0 => -1, ), '<API key>' => array ( ), ), 'uan' => array ( '<API key>' => 'NA', '<API key>' => 'NA', 'PossibleLength' => array ( 0 => -1, ), '<API key>' => array ( ), ), 'voicemail' => array ( '<API key>' => 'NA', '<API key>' => 'NA', 'PossibleLength' => array ( 0 => -1, ), '<API key>' => array ( ), ), '<API key>' => array ( '<API key>' => 'NA', '<API key>' => 'NA', 'PossibleLength' => array ( 0 => -1, ), '<API key>' => array ( ), ), 'id' => 'GL', 'countryCode' => 299, 'internationalPrefix' => '00', '<API key>' => false, 'numberFormat' => array ( 0 => array ( 'pattern' => '(\\d{2})(\\d{2})(\\d{2})', 'format' => '$1 $2 $3', '<API key>' => array ( ), '<API key>' => '', '<API key>' => '', '<API key>' => false, ), ), 'intlNumberFormat' => array ( ), 'mainCountryForCode' => false, 'leadingZeroPossible' => false, '<API key>' => false, );
#include "qlatincodec_p.h" #include "qlist.h" #ifndef QT_NO_TEXTCODEC QT_BEGIN_NAMESPACE QLatin1Codec::~QLatin1Codec() { } QString QLatin1Codec::convertToUnicode(const char *chars, int len, ConverterState *) const { if (chars == 0) return QString(); return QString::fromLatin1(chars, len); } QByteArray QLatin1Codec::convertFromUnicode(const QChar *ch, int len, ConverterState *state) const { const char replacement = (state && state->flags & <API key>) ? 0 : '?'; QByteArray r; r.resize(len); char *d = r.data(); int invalid = 0; for (int i = 0; i < len; ++i) { if (ch[i] > 0xff) { d[i] = replacement; ++invalid; } else { d[i] = (char)ch[i].cell(); } } if (state) { state->invalidChars += invalid; } return r; } QByteArray QLatin1Codec::name() const { return "ISO-8859-1"; } QList<QByteArray> QLatin1Codec::aliases() const { QList<QByteArray> list; list << "latin1" << "CP819" << "IBM819" << "iso-ir-100" << "csISOLatin1"; return list; } int QLatin1Codec::mibEnum() const { return 4; } QLatin15Codec::~QLatin15Codec() { } QString QLatin15Codec::convertToUnicode(const char* chars, int len, ConverterState *) const { if (chars == 0) return QString(); QString str = QString::fromLatin1(chars, len); QChar *uc = str.data(); while(len switch(uc->unicode()) { case 0xa4: *uc = 0x20ac; break; case 0xa6: *uc = 0x0160; break; case 0xa8: *uc = 0x0161; break; case 0xb4: *uc = 0x017d; break; case 0xb8: *uc = 0x017e; break; case 0xbc: *uc = 0x0152; break; case 0xbd: *uc = 0x0153; break; case 0xbe: *uc = 0x0178; break; default: break; } uc++; } return str; } QByteArray QLatin15Codec::convertFromUnicode(const QChar *in, int length, ConverterState *state) const { const char replacement = (state && state->flags & <API key>) ? 0 : '?'; QByteArray r; r.resize(length); char *d = r.data(); int invalid = 0; for (int i = 0; i < length; ++i) { uchar c; ushort uc = in[i].unicode(); if (uc < 0x0100) { if (uc > 0xa3) { switch(uc) { case 0xa4: case 0xa6: case 0xa8: case 0xb4: case 0xb8: case 0xbc: case 0xbd: case 0xbe: c = replacement; ++invalid; break; default: c = (unsigned char) uc; break; } } else { c = (unsigned char) uc; } } else { if (uc == 0x20ac) c = 0xa4; else if ((uc & 0xff00) == 0x0100) { switch(uc) { case 0x0160: c = 0xa6; break; case 0x0161: c = 0xa8; break; case 0x017d: c = 0xb4; break; case 0x017e: c = 0xb8; break; case 0x0152: c = 0xbc; break; case 0x0153: c = 0xbd; break; case 0x0178: c = 0xbe; break; default: c = replacement; ++invalid; } } else { c = replacement; ++invalid; } } d[i] = (char)c; } if (state) { state->remainingChars = 0; state->invalidChars += invalid; } return r; } QByteArray QLatin15Codec::name() const { return "ISO-8859-15"; } QList<QByteArray> QLatin15Codec::aliases() const { QList<QByteArray> list; list << "latin9"; return list; } int QLatin15Codec::mibEnum() const { return 111; } QT_END_NAMESPACE #endif // QT_NO_TEXTCODEC
# Written by Gustavo Niemeyer <niemeyer@conectiva.com> # This file is part of Smart Package Manager. # Smart Package Manager is free software; you can redistribute it and/or # your option) any later version. # Smart Package Manager is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # along with Smart Package Manager; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA from smart.transaction import Transaction, PolicyInstall, sortUpgrades from smart.transaction import INSTALL, REINSTALL from smart.option import OptionParser from smart.cache import Package from smart import * import string import re import os USAGE=_("smart install [options] package ...") DESCRIPTION=_(""" This command will install one or more packages in the system. If a new version of an already installed package is available, it will be selected for installation. """) def parse_options(argv): parser = OptionParser(usage=USAGE, description=DESCRIPTION, examples=EXAMPLES) parser.add_option("--stepped", action="store_true", help=_("split operation in steps")) parser.add_option("--urls", action="store_true", help=_("dump needed urls and don't commit operation")) parser.add_option("--download", action="store_true", help=_("download packages and don't commit operation")) parser.add_option("--explain", action="store_true", help=_("include additional information about changes," "when possible")) parser.add_option("-y", "--yes", action="store_true", help=_("do not ask for confirmation")) parser.add_option("--dump", action="store_true", help=_("dump package names and versions to stderr but " "don't commit operation")) opts, args = parser.parse_args(argv) opts.args = args return opts def main(ctrl, opts): if opts.explain: sysconf.set("explain-changesets", True, soft=True) urls = [] for arg in opts.args[:]: if (os.path.isfile(arg) and '/' in arg or filter(None, hooks.call("check-package-file", arg))): ctrl.addFileChannel(arg) opts.args.remove(arg) elif ":/" in arg: urls.append(arg) if urls: succ, fail = ctrl.downloadURLs(urls, _("packages"), targetdir=os.getcwd()) if fail: raise Error, _("Failed to download packages:\n") + \ "\n".join([" %s: %s" % (url, fail[url]) for url in fail]) for url, file in succ.items(): ctrl.addFileChannel(file) opts.args.remove(url) ctrl.reloadChannels() cache = ctrl.getCache() trans = Transaction(cache, PolicyInstall) for channel in ctrl.getFileChannels(): for loader in channel.getLoaders(): for pkg in loader.getPackages(): if pkg.installed: raise Error, _("%s is already installed") % pkg trans.enqueue(pkg, INSTALL) for arg in opts.args: ratio, results, suggestions = ctrl.search(arg) if not results: if suggestions: dct = {} for r, obj in suggestions: if isinstance(obj, Package): dct[obj] = True else: dct.update(dict.fromkeys(obj.packages, True)) raise Error, _("'%s' matches no packages. " "Suggestions:\n%s") % \ (arg, "\n".join([" "+str(x) for x in dct])) else: raise Error, _("'%s' matches no packages") % arg pkgs = [] for obj in results: if isinstance(obj, Package): pkgs.append(obj) if not pkgs: installed = False names = {} for obj in results: for pkg in obj.packages: if pkg.installed: iface.warning(_("%s (for %s) is already installed") % (pkg, arg)) installed = True break else: pkgs.append(pkg) names[pkg.name] = True else: continue break if installed: continue if len(names) > 1: raise Error, _("There are multiple matches for '%s':\n%s") % \ (arg, "\n".join([" "+str(x) for x in pkgs])) if len(pkgs) > 1: sortUpgrades(pkgs) names = {} for pkg in pkgs: names.setdefault(pkg.name, []).append(pkg) for name in names: pkg = names[name][0] if pkg.installed: iface.warning(_("%s is already installed") % pkg) else: trans.enqueue(pkg, INSTALL) iface.showStatus(_("Computing transaction...")) trans.run() iface.hideStatus() if trans: confirm = not opts.yes print opts.urls, opts.dump, opts.download, opts.stepped, confirm if opts.urls: ctrl.dumpTransactionURLs(trans) elif opts.dump: ctrl.<API key>(trans, install=True) elif opts.download: ctrl.downloadTransaction(trans, confirm=confirm) elif opts.stepped: ctrl.<API key>(trans, confirm=confirm) else: ctrl.commitTransaction(trans, confirm=confirm) # vim:ts=4:sw=4:et
<?php defined('_JEXEC') or die('Restricted access'); class <API key> extends JModelAdmin { protected $_compo = 'com_cp3d'; protected $_context = 'lignecommande'; public $typeAlias = 'com_cp3d.lignecommande'; public function getTable($type = 'LigneCommande', $prefix = 'Cp3dTable', $config = array()) { return JTable::getInstance($type, $prefix, $config); } public function getForm($data = array(), $loadData = true) { $form = $this->loadForm($this->typeAlias, $this->_context, array('control'=>'jform', 'load_data'=>$loadData)); if (empty($form)) { return false; } return $form; } protected function loadFormData() { $data = JFactory::getApplication()->getUserState($this->_compo.'.edit.'.$this->_context.'.data', array()); if (empty($data)) { $data = $this->getItem(); } return $data; } protected function prepareTable($table) { $table->alias = JApplication::stringURLSafe($table->alias); if (empty($table->alias)) { $table->alias = JApplication::stringURLSafe($table->nom); } } }
.footer-contact-icon i, .footer-addr-icon, .footer-blog-post:hover h3 a , .<API key> ul li a, .<API key> ul li a:hover, .footer-copyright p a:hover, .page-breadcrumb > li.active a, .blog-lg-area-left h3 > a:hover, .blog-lg-area-right h3 > a:hover, .blog-lg-area-full h3 > a:hover, p.wp-caption-text a, .blog-author span, .comment-date a:hover, .reply a, .reply a:hover, .blog-post-lg a:hover, .blog-tags-lg a:hover, .sidebar-blog-post:hover h3 a , .sidebar-widget div#calendar_wrap table > thead > tr > th, ul.post-content li:hover a, .blog-pagination a, .media-body th a:hover, .media-body dd a:hover, .media-body p a:hover, .media-body li a:hover, .sidebar-widget a:hover, .<API key> a:hover, .comment-respond a:hover, .error-404 h1, .comment-author-link a:hover, table a, table a:hover, .blog-sm-area h3 > a:hover, .blog-sm-area h3 > a:focus, .blog-post-sm a:hover, .blog-tags-sm a:hover, .service-icon i, .page-breadcrumb .active, .<API key> div#calendar_wrap table > thead > tr > th,.blog-lg-area-left p > a, .blog-lg-area-right p > a, .blog-lg-area-full p > a, .sidebar-widget > ul > li > a:hover, .blog-lg-area-left dl > dd > a, .blog-lg-area-right dl > dd > a, .blog-lg-area-full dl > dd > a { color: #395ca3; } /* Background color */ .footer-widget-tags a:hover, .blog-post-date-area .date, .blog-btn-lg,.blogdetail-btn a, .cont-btn a, .blogdetail-btn a:hover, .cont-btn a:hover, .sidebar-widget > .input-group > .input-group-addon, .sidebar-widget-tags a:hover, .blog-pagination a:hover, .blog-pagination a.active, a.error-btn, .hc_scrollup, .tagcloud a:hover, .form-submit input,.<API key> a:hover, .<API key> a.active, .media-body input[type=submit], .sidebar-widget input[type=submit], .callout-btn2, .blog-btn-sm, a.hrtl-btn, .slide-btn-sm,.<API key> { background-color: #395ca3; } .footer-widget-tags a:hover, .tagcloud a:hover , .<API key> a:hover, .<API key> a.active, .media-body input[type=submit], .sidebar-widget input[type=submit] { border: 1px solid #395ca3; } .blog-lg-box img { border-bottom: 3px solid #395ca3; } .blog-btn-lg, .blog-btn-sm, a.hrtl-btn, .form-submit input, a.error-btn, .callout-btn2, .blogdetail-btn a, .cont-btn a, .slide-btn-sm { box-shadow: 0 3px 0 0 #2a4987; } .quote-content blockquote { border-left: 5px solid #395ca3; } .sidebar-widget > .input-group > .input-group-addon { border: 1px solid #395ca3; } .sidebar-widget-tags a:hover { border: 1px solid #395ca3; } /*Blog Pagination*/ .blog-pagination a:hover, .blog-pagination a.active { border: 1px solid #395ca3; } a.error-btn { text-shadow: 0 1px 0 rgba(0, 0, 0, 0.1); } .<API key> { border-bottom: 5px solid #395ca3;} #post-559 { border-left: 22px solid #395ca3; } .page-title a:hover {color: #395ca3 !important;}
function base64_decode (data) { var b64 = "<API key>+/="; var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = []; if (!data) { return data; } data += ''; do { // unpack four hexets into three octets using index points in b64 h1 = b64.indexOf(data.charAt(i++)); h2 = b64.indexOf(data.charAt(i++)); h3 = b64.indexOf(data.charAt(i++)); h4 = b64.indexOf(data.charAt(i++)); bits = h1 << 18 | h2 << 12 | h3 << 6 | h4; o1 = bits >> 16 & 0xff; o2 = bits >> 8 & 0xff; o3 = bits & 0xff; if (h3 == 64) { tmp_arr[ac++] = String.fromCharCode(o1); } else if (h4 == 64) { tmp_arr[ac++] = String.fromCharCode(o1, o2); } else { tmp_arr[ac++] = String.fromCharCode(o1, o2, o3); } } while (i < data.length); dec = tmp_arr.join(''); return dec; } function rawurldecode (str) { return decodeURIComponent((str + '').replace(/%(?![\da-f]{2})/gi, function () { // PHP tolerates poorly formed escape sequences return '%25'; })); } jQuery(document).ready(function($){ var galleries = $('.ilightbox_gallery'), jetpackGalleries = $('.tiled-gallery'), nextGenGalleries = $('.ngg-galleryoverview'); if(galleries.length){ galleries.each(function(){ var t = $(this), kid = $('a[source]', t), options = t.data("options") && eval("(" + t.data("options") + ")") || {}; kid.iLightBox(options); }); } if(jetpackGalleries.length && ILIGHTBOX.jetPack){ jetpackGalleries.each(function(){ var t = $(this), kid = $('a', t), options = ILIGHTBOX.options && eval("(" + rawurldecode(ILIGHTBOX.options) + ")") || {}; options.attr = 'source'; kid.each(function(i){ var $this = $(this), $img = $('img', $this), origFile = $img.data('orig-file'); $this.attr('source', origFile); }); kid.iLightBox(options); }); } if(nextGenGalleries.length && ILIGHTBOX.nextGEN){ nextGenGalleries.each(function(){ var t = $(this), kid = $('.<API key> a', t), options = ILIGHTBOX.options && eval("(" + rawurldecode(ILIGHTBOX.options) + ")") || {}; kid.each(function(i){ var $this = $(this); $this[0].onclick = null; }); kid.iLightBox(options); }); } $(document).on('click', '.<API key>', function(){ var t = $(this), slides = t.data("slides") && eval("(" + rawurldecode(base64_decode(t.data("slides"))) + ")") || []; options = t.data("options") && eval("(" + rawurldecode(base64_decode(t.data("options"))) + ")") || {}; $.iLightBox(slides, options); }); });
#ifdef QT_HAVE_SSE #include <private/qdrawhelper_sse_p.h> const <API key> <API key>[] = { <API key><QSSEIntrinsics>, <API key><QSSEIntrinsics>, <API key><QSSEIntrinsics>, <API key><QSSEIntrinsics>, 0, <API key><QSSEIntrinsics>, <API key><QSSEIntrinsics>, <API key><QSSEIntrinsics>, <API key><QSSEIntrinsics>, <API key><QSSEIntrinsics>, <API key><QSSEIntrinsics>, comp_func_solid_XOR<QSSEIntrinsics>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key> }; const CompositionFunction <API key>[] = { <API key><QSSEIntrinsics>, <API key><QSSEIntrinsics>, comp_func_Clear<QSSEIntrinsics>, comp_func_Source<QSSEIntrinsics>, 0, comp_func_SourceIn<QSSEIntrinsics>, <API key><QSSEIntrinsics>, comp_func_SourceOut<QSSEIntrinsics>, <API key><QSSEIntrinsics>, <API key><QSSEIntrinsics>, <API key><QSSEIntrinsics>, comp_func_XOR<QSSEIntrinsics>, comp_func_Plus, comp_func_Multiply, comp_func_Screen, comp_func_Overlay, comp_func_Darken, comp_func_Lighten, <API key>, comp_func_ColorBurn, comp_func_HardLight, comp_func_SoftLight, <API key>, comp_func_Exclusion }; void <API key>(int count, const QSpan *spans, void *userData) { <API key><QSSEIntrinsics>(count, spans, userData, (<API key>*)<API key>); } void qt_memfill32_sse(quint32 *dest, quint32 value, int count) { return <API key><QSSEIntrinsics>(dest, value, count); } void qt_bitmapblit16_sse(QRasterBuffer *rasterBuffer, int x, int y, quint32 color, const uchar *src, int width, int height, int stride) { return <API key><QSSEIntrinsics>(rasterBuffer, x,y, color, src, width, height, stride); } #endif // QT_HAVE_SSE
<?php include('header.php') ?> <section class="btws-main-content"> <div class="btws-center"> <h1>Ceci n'est pas un titre, surtout pas d'archive</h1> <p>Maecenas faucibus mollis interdum. Donec id elit non mi porta gravida at eget metus. Nulla vitae elit libero, a pharetra augue. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.</p> </div> </section> <?php include('footer.php') ?>
#include "filter.h" #include <regex.h> /* draft */ #define HOST_REGEX "([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})" typedef struct f2b_regex_t { struct f2b_regex_t *next; char pattern[PATTERN_MAX]; int matches; regex_t regex; } f2b_regex_t; struct _config { char id[ID_MAX]; char error[256]; bool icase; f2b_regex_t *regexps; f2b_regex_t *statp; }; cfg_t * create(const char *id) { cfg_t *cfg = NULL; if ((cfg = calloc(1, sizeof(cfg_t))) == NULL) return NULL; strlcpy(cfg->id, id, sizeof(cfg->id)); return cfg; } bool config(cfg_t *cfg, const char *key, const char *value) { assert(cfg != NULL); assert(key != NULL); assert(value != NULL); if (strcmp(key, "icase") == 0) { cfg->icase = (strcmp(value, "yes") == 0) ? true : false; return true; } return false; } bool append(cfg_t *cfg, const char *pattern) { f2b_regex_t *regex = NULL; int flags = REG_EXTENDED; size_t bufsize; char *buf = NULL; char *token = NULL; assert(pattern != NULL); if (cfg->icase) flags |= REG_ICASE; if ((token = strstr(pattern, HOST_TOKEN)) == NULL) return false; bufsize = strlen(pattern) + strlen(HOST_REGEX) + 1; if ((buf = alloca(bufsize)) == NULL) return false; memset(buf, 0x0, bufsize); memcpy(buf, pattern, token - pattern); strlcat(buf, HOST_REGEX, bufsize); strlcat(buf, token + strlen(HOST_TOKEN), bufsize); if ((regex = calloc(1, sizeof(f2b_regex_t))) == NULL) return false; if (regcomp(&regex->regex, buf, flags) == 0) { regex->next = cfg->regexps; cfg->regexps = regex; strlcpy(regex->pattern, pattern, sizeof(regex->pattern)); return true; } free(regex); return false; } bool ready(cfg_t *cfg) { assert(cfg != NULL); if (cfg->regexps) return true; return false; } bool stats(cfg_t *cfg, int *matches, char **pattern, bool reset) { assert(cfg != NULL); if (reset) cfg->statp = cfg->regexps; if (cfg->statp) { *matches = cfg->statp->matches; *pattern = cfg->statp->pattern; cfg->statp = cfg->statp->next; return true; } return false; } const char * error(cfg_t *cfg) { assert(cfg != NULL); return cfg->error; } bool match(cfg_t *cfg, const char *line, char *buf, size_t buf_size) { f2b_regex_t *r = NULL; size_t match_len = 0; regmatch_t match[2]; assert(cfg != NULL); assert(line != NULL); assert(buf != NULL); for (r = cfg->regexps; r != NULL; r = r->next) { if (regexec(&r->regex, line, 2, &match[0], 0) != 0) continue; /* matched */ r->matches++; match_len = match[1].rm_eo - match[1].rm_so; assert(buf_size > match_len); memcpy(buf, &line[match[1].rm_so], match_len); buf[match_len] = '\0'; buf[buf_size - 1] = '\0'; return true; } return false; } void flush(cfg_t *cfg) { f2b_regex_t *next = NULL, *r = NULL; assert(cfg != NULL); for (r = cfg->regexps; r != NULL; r = next) { next = r->next; regfree(&r->regex); free(r); } cfg->regexps = NULL; } void destroy(cfg_t *cfg) { assert(cfg != NULL); flush(cfg); free(cfg); }
/* SEMC:modified */ #include <asm/mach-types.h> #include <linux/platform_device.h> #include <linux/gpio_event.h> #define <API key> 36 static unsigned int es209ra_row_gpios[] = { 33, 34, 35 }; static unsigned int es209ra_col_gpios[] = { 38, 39, 40, 41, 42 }; /* es209ra: 38: KEYSENSE_N(0) 39: KEYSENSE_N(1) 40: KEYSENSE_N(2) 41: KEYSENSE_N(3) 42: KEYSENSE_N(4) 35: KYPD_20 34: KYPD_17 33: KYPD_15 36: PowerKey */ #define KEYMAP_INDEX(row, col) ((row)*ARRAY_SIZE(es209ra_col_gpios) + (col)) #ifdef CONFIG_ES209RA_LB static const unsigned short es209ra_keymap[ARRAY_SIZE(es209ra_col_gpios) * ARRAY_SIZE(es209ra_row_gpios)] = { [KEYMAP_INDEX(0, 0)] = KEY_VOLUMEUP, /* volume up(115) */ [KEYMAP_INDEX(0, 1)] = KEY_VOLUMEDOWN, /* volume down(114) */ [KEYMAP_INDEX(0, 2)] = KEY_CAMERA, /* camera(212) */ [KEYMAP_INDEX(0, 3)] = KEY_EMAIL, /* AF(215) */ [KEYMAP_INDEX(0, 4)] = KEY_COFFEE, /* lock(152) */ [KEYMAP_INDEX(1, 0)] = KEY_SEND, /* send(231) */ [KEYMAP_INDEX(1, 1)] = KEY_KBDILLUMDOWN, /* menu(229) */ [KEYMAP_INDEX(1, 2)] = KEY_HOME, /* home(102) */ [KEYMAP_INDEX(1, 3)] = KEY_BACK, /* back(158) */ [KEYMAP_INDEX(1, 4)] = KEY_END, /* end(107) */ [KEYMAP_INDEX(2, 0)] = KEY_UP, /* up(103) */ [KEYMAP_INDEX(2, 1)] = KEY_DOWN, /* down(108) */ [KEYMAP_INDEX(2, 2)] = KEY_LEFT, /* left(105) */ [KEYMAP_INDEX(2, 3)] = KEY_RIGHT, /* right(106) */ [KEYMAP_INDEX(2, 4)] = KEY_REPLY /* click(232) */ }; #else static const unsigned short es209ra_keymap[ARRAY_SIZE(es209ra_col_gpios) * ARRAY_SIZE(es209ra_row_gpios)] = { [KEYMAP_INDEX(0, 0)] = KEY_VOLUMEUP, /* volume up(115) */ [KEYMAP_INDEX(0, 1)] = KEY_VOLUMEDOWN, /* volume down(114) */ [KEYMAP_INDEX(0, 2)] = KEY_CAMERA, /* camera(212) */ [KEYMAP_INDEX(0, 3)] = KEY_EMAIL, /* AF(215) */ [KEYMAP_INDEX(1, 1)] = KEY_KBDILLUMDOWN, /* menu(229) */ [KEYMAP_INDEX(1, 2)] = KEY_HOME, /* home(102) */ [KEYMAP_INDEX(1, 3)] = KEY_BACK, /* back(158) */ }; #endif static struct <API key> es209ra_matrix_info = { .info.func = <API key>, .keymap = es209ra_keymap, .output_gpios = es209ra_row_gpios, .input_gpios = es209ra_col_gpios, .noutputs = ARRAY_SIZE(es209ra_row_gpios), .ninputs = ARRAY_SIZE(es209ra_col_gpios), /* SEMC:SYS: DMS DMS00705986 (Chage to 500ms) start */ .settle_time.tv_nsec = 500 * NSEC_PER_USEC, /* SEMC:SYS: DMS DMS00705986 end */ .poll_time.tv_nsec = 20 * NSEC_PER_MSEC, /* SEMC:SYS DMS00655868 Keypad driver to support different key push at a time - start */ .flags = <API key> | <API key> /*| <API key>*/ /* SEMC:SYS DMS00655868 Keypad driver to support different key push at a time - end */ }; static struct <API key> <API key>[] = { { <API key>, KEY_POWER } /* power(116) */ }; static struct <API key> <API key> = { .info.func = <API key>, .flags = 0, .type = EV_KEY, .keymap = <API key>, .keymap_size = ARRAY_SIZE(<API key>) }; static struct gpio_event_info *es209ra_keypad_info[] = { &es209ra_matrix_info.info, &<API key>.info }; static struct <API key> es209ra_keypad_data = { .name = "es209ra_keypad", .info = es209ra_keypad_info, .info_count = ARRAY_SIZE(es209ra_keypad_info) }; struct platform_device <API key> = { .name = GPIO_EVENT_DEV_NAME, .id = -1, .dev = { .platform_data = &es209ra_keypad_data, }, };
/** * A probe which records the value of an incoming signal. */ #include "sark.h" #include "spin1_api.h" #include "common.h" struct { uint sim_length; uint input_key; uchar recording[]; } *config; uint last_input = 0; void on_tick(uint ticks, uint arg1) { // Terminate after the specified duration if (ticks >= config->sim_length) { spin1_exit(0); return; } // Record the value near the end of the timestep (so it is more likely we saw // the input value after it changed in the timestep). spin1_delay_us(700); config->recording[ticks/8] |= last_input << (ticks % 8); } void on_mc_packet(uint key, uint arg1) { if ((key & 0x7FFFFFFF) == config->input_key) { last_input = key >> 31; } } void c_main(void) { // Discover the config for this core. // XXX: For simplicity, in this example application we (very infficiently) // access SDRAM directly via this pointer instead of DMAing it into local // memroy. uint core = spin1_get_core_id(); config = sark_tag_ptr(core, 0); // Initially clear the recording area for (int i = 0; i < (config->sim_length + 7)/8; i++) config->recording[i] = 0; <API key>(1000); // 1ms spin1_callback_on(TIMER_TICK, on_tick, 1); spin1_callback_on(MC_PACKET_RECEIVED, on_mc_packet, -1); spin1_start(SYNC_WAIT); }
package com.mobilerobots.Aria; public class <API key> extends ArRangeDevice { /* (begin code from javabody_derived typemap) */ private long swigCPtr; /* for internal use by swig only */ public <API key>(long cPtr, boolean cMemoryOwn) { super(AriaJavaJNI.<API key>(cPtr), cMemoryOwn); swigCPtr = cPtr; } /* for internal use by swig only */ public static long getCPtr(<API key> obj) { return (obj == null) ? 0 : obj.swigCPtr; } /* (end code from javabody_derived typemap) */ protected void finalize() { delete(); } public synchronized void delete() { if(swigCPtr != 0 && swigCMemOwn) { swigCMemOwn = false; AriaJavaJNI.<API key>(swigCPtr); } swigCPtr = 0; super.delete(); } public SWIGTYPE_p_void runThread(SWIGTYPE_p_void arg) { long cPtr = AriaJavaJNI.<API key>(swigCPtr, this, SWIGTYPE_p_void.getCPtr(arg)); return (cPtr == 0) ? null : new SWIGTYPE_p_void(cPtr, false); } public void run() { AriaJavaJNI.<API key>(swigCPtr, this); } public void runAsync() { AriaJavaJNI.<API key>(swigCPtr, this); } public void stopRunning() { AriaJavaJNI.<API key>(swigCPtr, this); } public boolean getRunning() { return AriaJavaJNI.<API key>(swigCPtr, this); } public boolean getRunningWithLock() { return AriaJavaJNI.<API key>(swigCPtr, this); } public int lockDevice() { return AriaJavaJNI.<API key>(swigCPtr, this); } public int tryLockDevice() { return AriaJavaJNI.<API key>(swigCPtr, this); } public int unlockDevice() { return AriaJavaJNI.<API key>(swigCPtr, this); } }
# CMAKE generated file: DO NOT EDIT! # Generated by "Unix Makefiles" Generator, CMake Version 2.8 # Default target executed when no arguments are given to make. default_target: all .PHONY : default_target # Special targets provided by cmake. # Disable implicit rules so canonical targets will work. .SUFFIXES: # Remove some rules from gmake that .SUFFIXES does not remove. SUFFIXES = .SUFFIXES: .<API key> # Suppress display of executed commands. $(VERBOSE).SILENT: # A target that is always out of date. cmake_force: .PHONY : cmake_force # Set environment variables for the build. # The shell in which to execute make rules. SHELL = /bin/sh # The CMake executable. CMAKE_COMMAND = /usr/bin/cmake # The command to remove a file. RM = /usr/bin/cmake -E remove -f # The top-level source directory on which CMake was run. CMAKE_SOURCE_DIR = /home/shamp03/src/xtalopt # The top-level build directory on which CMake was run. CMAKE_BINARY_DIR = /home/shamp03/src/xtalopt/build # Targets provided globally by CMake. # Special rule for the target edit_cache edit_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running interactive CMake command-line interface..." /usr/bin/cmake -i . .PHONY : edit_cache # Special rule for the target edit_cache edit_cache/fast: edit_cache .PHONY : edit_cache/fast # Special rule for the target install install: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..." /usr/bin/cmake -P cmake_install.cmake .PHONY : install # Special rule for the target install install/fast: preinstall/fast @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..." /usr/bin/cmake -P cmake_install.cmake .PHONY : install/fast # Special rule for the target install/local install/local: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..." /usr/bin/cmake -<API key>=1 -P cmake_install.cmake .PHONY : install/local # Special rule for the target install/local install/local/fast: install/local .PHONY : install/local/fast # Special rule for the target install/strip install/strip: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..." /usr/bin/cmake -<API key>=1 -P cmake_install.cmake .PHONY : install/strip # Special rule for the target install/strip install/strip/fast: install/strip .PHONY : install/strip/fast # Special rule for the target <API key> <API key>: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Available install components are: \"Unspecified\"" .PHONY : <API key> # Special rule for the target <API key> <API key>/fast: <API key> .PHONY : <API key>/fast # Special rule for the target rebuild_cache rebuild_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." /usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : rebuild_cache # Special rule for the target rebuild_cache rebuild_cache/fast: rebuild_cache .PHONY : rebuild_cache/fast # The main all target all: <API key> cd /home/shamp03/src/xtalopt/build && $(CMAKE_COMMAND) -E <API key> /home/shamp03/src/xtalopt/build/CMakeFiles /home/shamp03/src/xtalopt/build/src/CMakeFiles/progress.marks cd /home/shamp03/src/xtalopt/build && $(MAKE) -f CMakeFiles/Makefile2 src/all $(CMAKE_COMMAND) -E <API key> /home/shamp03/src/xtalopt/build/CMakeFiles 0 .PHONY : all # The main clean target clean: cd /home/shamp03/src/xtalopt/build && $(MAKE) -f CMakeFiles/Makefile2 src/clean .PHONY : clean # The main clean target clean/fast: clean .PHONY : clean/fast # Prepare targets for installation. preinstall: all cd /home/shamp03/src/xtalopt/build && $(MAKE) -f CMakeFiles/Makefile2 src/preinstall .PHONY : preinstall # Prepare targets for installation. preinstall/fast: cd /home/shamp03/src/xtalopt/build && $(MAKE) -f CMakeFiles/Makefile2 src/preinstall .PHONY : preinstall/fast # clear depends depend: cd /home/shamp03/src/xtalopt/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 .PHONY : depend # Help Target help: @echo "The following are some of the valid targets for this Makefile:" @echo "... all (the default if no target is provided)" @echo "... clean" @echo "... depend" @echo "... edit_cache" @echo "... install" @echo "... install/local" @echo "... install/strip" @echo "... <API key>" @echo "... rebuild_cache" .PHONY : help # Special targets to cleanup operation of make. # Special rule to run CMake to check the build system integrity. # No rule that depends on this can have commands that come from listfiles # because they might be regenerated. <API key>: cd /home/shamp03/src/xtalopt/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 .PHONY : <API key>
#ifndef ENCRYPT_H #define ENCRYPT_H #include <string> #include <stdint.h> #include <stdlib.h> typedef enum { step_a, step_b, step_c, step_d } base64_decodestep; typedef struct { base64_decodestep step; char plainchar; } base64_decodestate; class Base64 { int base64_decode_value(char value_in) { static const char decoding[] = { 62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61, -1,-1,-1,-2,-1,-1,-1, 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25, -1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41, 42,43,44,45,46,47,48,49,50,51 }; static const char decoding_size = sizeof(decoding); value_in -= 43; if (value_in < 0 || value_in >= decoding_size) return -1; return decoding[(int)value_in]; } void <API key>(base64_decodestate* state_in) { state_in->step = step_a; state_in->plainchar = 0; } int base64_decode_block(const char* code_in, const int length_in, char* plaintext_out, base64_decodestate* state_in) { const char* codechar = code_in; char* plainchar = plaintext_out; char fragment; *plainchar = state_in->plainchar; switch (state_in->step) { while (1) { case step_a: do { if (codechar == code_in+length_in) { state_in->step = step_a; state_in->plainchar = *plainchar; return plainchar - plaintext_out; } fragment = (char)base64_decode_value(*codechar++); } while (fragment < 0); *plainchar = (fragment & 0x03f) << 2; case step_b: do { if (codechar == code_in+length_in) { state_in->step = step_b; state_in->plainchar = *plainchar; return plainchar - plaintext_out; } fragment = (char)base64_decode_value(*codechar++); } while (fragment < 0); *plainchar++ |= (fragment & 0x030) >> 4; *plainchar = (fragment & 0x00f) << 4; case step_c: do { if (codechar == code_in+length_in) { state_in->step = step_c; state_in->plainchar = *plainchar; return plainchar - plaintext_out; } fragment = (char)base64_decode_value(*codechar++); } while (fragment < 0); *plainchar++ |= (fragment & 0x03c) >> 2; *plainchar = (fragment & 0x003) << 6; case step_d: do { if (codechar == code_in+length_in) { state_in->step = step_d; state_in->plainchar = *plainchar; return plainchar - plaintext_out; } fragment = (char)base64_decode_value(*codechar++); } while (fragment < 0); *plainchar++ |= (fragment & 0x03f); } } /* control should not reach here */ return plainchar - plaintext_out; } public: int decode(char value_in) { return base64_decode_value(value_in); } int decode(const char* code_in, const int length_in, char* plaintext_out) { base64_decodestate _state; <API key>(&_state); int len = base64_decode_block(code_in, length_in, plaintext_out, &_state); <API key>(&_state); return len; } static char* encode(const unsigned char *data, size_t input_len, size_t& output_len); static char* decode(const char *data, size_t input_len, size_t& output_len); }; #endif
&lt;div class=&quot;well well-lg&quot;&gt;Look, I'm in a large well!&lt;/div&gt;
<?php $infosoeuvres_mb = new WPAlchemy_MetaBox(array ( 'id' => '_infosoeuvres', 'title' => 'Informations sur l\'oeuvres', 'types' => array('post'), 'template' => <API key>() . '/metaboxes/infosoeuvres-meta.php', )); /* eof */
// * MajorLabel - Guido Goluke // * Email: info@majorlabel.nl // * Authors: // * Guido Goluke, <info@majorlabel.nl> // * This program is free software; you can redistribute it and/or modify // * (at your option) any later version. // * This program is distributed in the hope that it will be useful, // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // * along with this program; if not, write to the Free Software // * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // * Or read it online: http://www.gnu.org/licenses/licenses.html#GPL function addToolBar(editor, moduleDir, AceModes, currentMode, cssPrefMode) { // Create the toolbar DIV $(editor.container).parent().prepend('<div id="AceToolbar"></div>'); // Set the toolbar width to the editor width $('#AceToolbar').css('width', $('.ace_editor').outerWidth()); // Create the bottombar DIV $(editor.container).parent().append('<div id="AceBottombar"></div>'); $('#AceBottombar').css('width', $('.ace_editor').outerWidth()); // Catch a window resize $(window).resize(function(){ $('#AceBottombar, #AceToolbar').css('width', $('.ace_editor').outerWidth()); }); // Autoload the current mode, that is the mode from the textarea 'data-cms-lang' attribute // If the 'data-cms-lang' attribute is CSS, use the cssPrefMode if (currentMode == 'css') { $('head').append('<script src="'+moduleDir+'/lib/Ace/src-min/mode-'+cssPrefMode+'.js></script>'); editor.getSession().setMode('ace/mode/'+cssPrefMode); var selectedMode = cssPrefMode; } else { $('head').append('<script src="'+moduleDir+'/lib/Ace/src-min/mode-'+currentMode+'.js></script>'); editor.getSession().setMode('ace/mode/'+currentMode); var selectedMode = currentMode; } // Append the mode select to the toolbar $('#AceToolbar').prepend('<select class="AceModeSelect"></select>'); // Fill the mode select with the selected modes $.each(AceModes, function(Label, AceMode){ $('.AceModeSelect').prepend('<option value="'+AceMode+'">'+Label+'</option>'); }); // Update the dropdown with the current mode selected $('.AceModeSelect').children().each(function(i){ var optionValue = $(this).attr('value'); if (optionValue == selectedMode) { $('.AceModeSelect option[value^='+optionValue+']').attr('selected','selected'); return; } }); // Automatically load the selected mode file, append it to the head and set the mode // When changing the selection $('.AceModeSelect').change(function(){ var mode = $('.AceModeSelect').val(); $('head').append('<script src="'+moduleDir+'/lib/Ace/src-min/mode-'+mode+'.js></script>'); editor.getSession().setMode('ace/mode/'+mode); }); // add a slider for the text size $('#AceToolbar').append('<div class="AceTextSize"><input type="range" min="12" max="20" value="16" step="1" id="AceTextSize"></div>'); // Set the default text size $('.ace_editor').css('font-size', $('#AceTextSize').val()+'px'); // Make the slider change the text size in the editor $('#AceTextSize').change(function(){ $('.ace_editor').css('font-size', $('#AceTextSize').val()+'px'); }); // jump to line input field $('#AceToolbar').append('<input class="AceJumpToLine" size"="70" placeholder="type line number" type="text">'); $('.AceJumpToLine').keyup(function(){ editor.resize(true); editor.scrollToLine($('.AceJumpToLine').val(), true, true, function () {}); editor.gotoLine($('.AceJumpToLine').val(), 0, true); }); } function aceResize() { $('.ace_editor').resizable({ handles: 'e,s' }); }
#include <stdlib.h> #include <uwifi/wlan_util.h> #include "display.h" #include "main.h" #include "network.h" #define COL_BAND2 23 static bool set_ht40plus; void update_channel_win(WINDOW *win) { int l = 2; box(win, 0 , 0); print_centered(win, 0, 39, " Channel Settings "); wattron(win, WHITE); for (int b = 0; b < <API key>(&conf.intf.channels); b++) { const struct uwifi_band* bp = <API key>(&conf.intf.channels, b); int c = <API key>(&conf.intf.channels, b, 0); int col = <API key>(&conf.intf.channels, c) > 14 ? COL_BAND2 : 2; wattron(win, A_BOLD); mvwprintw(win, 2, col, "%s: %s", col == 2 ? "2.4GHz" : "5GHz", <API key>(bp->max_chan_width, -1)); if (bp->streams_rx || bp->streams_tx) wprintw(win, " %dx%d", bp->streams_rx, bp->streams_tx); wattroff(win, A_BOLD); l = 3; for (int i = 0; (c = <API key>(&conf.intf.channels, b, i)) != -1; i++) { if (c == conf.intf.channel_idx) wattron(win, CYAN); else wattron(win, WHITE); mvwprintw(win, l++, col, "%s", <API key>(&conf.intf.channels, c)); } } wattroff(win, WHITE); l = 18; wattron(win, A_BOLD); mvwprintw(win, l++, 2, "s: [%c] Scan", CHECKED(conf.intf.channel_scan)); wattroff(win, A_BOLD); mvwprintw(win, l++, 2, "d: Dwell: %d ms ", conf.intf.channel_time/1000); mvwprintw(win, l++, 2, "u: Upper limit: %d ", conf.intf.channel_max); l++; wattron(win, A_BOLD); mvwprintw(win, l++, 2, "m: Set channel: %d ", wlan_freq2chan(conf.intf.channel_set.freq)); wattroff(win, A_BOLD); mvwprintw(win, l++, 2, "1: [%c] 20 (no HT)", CHECKED(conf.intf.channel_set.width == CHAN_WIDTH_20_NOHT)); mvwprintw(win, l++, 2, "2: [%c] HT20", CHECKED(conf.intf.channel_set.width == CHAN_WIDTH_20)); mvwprintw(win, l++, 2, "4: [%c] HT40-", CHECKED(conf.intf.channel_set.width == CHAN_WIDTH_40 && !set_ht40plus)); mvwprintw(win, l++, 2, "5: [%c] HT40+", CHECKED(conf.intf.channel_set.width == CHAN_WIDTH_40 && set_ht40plus)); mvwprintw(win, l++, 2, "8: [%c] VHT80", CHECKED(conf.intf.channel_set.width == CHAN_WIDTH_80)); mvwprintw(win, l++, 2, "6: [%c] VHT160", CHECKED(conf.intf.channel_set.width == CHAN_WIDTH_160)); print_centered(win, <API key>, CHANNEL_WIN_WIDTH, "[ Press keys and ENTER to apply ]"); wrefresh(win); } bool channel_input(WINDOW *win, int c) { char buf[6]; int x; int new_idx = -1; switch (c) { case 's': case 'S': conf.intf.channel_scan = conf.intf.channel_scan ? 0 : 1; break; case 'd': case 'D': echo(); curs_set(1); mvwgetnstr(win, 19, 12, buf, 6); curs_set(0); noecho(); sscanf(buf, "%d", &x); conf.intf.channel_time = x*1000; break; case 'u': case 'U': echo(); curs_set(1); mvwgetnstr(win, 20, 18, buf, 6); curs_set(0); noecho(); sscanf(buf, "%d", &x); conf.intf.channel_max = x; break; case 'm': case 'M': echo(); curs_set(1); mvwgetnstr(win, 22, 18, buf, 3); curs_set(0); noecho(); sscanf(buf, "%d", &x); conf.intf.channel_set.freq = wlan_chan2freq(x); break; case '1': conf.intf.channel_set.width = CHAN_WIDTH_20_NOHT; break; case '2': conf.intf.channel_set.width = CHAN_WIDTH_20; break; case '4': conf.intf.channel_set.width = CHAN_WIDTH_40; set_ht40plus = false; break; case '5': conf.intf.channel_set.width = CHAN_WIDTH_40; set_ht40plus = true; break; case '8': conf.intf.channel_set.width = CHAN_WIDTH_80; break; case '6': conf.intf.channel_set.width = CHAN_WIDTH_160; break; case '\r': case KEY_ENTER: /* used to close win, too */ new_idx = <API key>(&conf.intf.channels, conf.intf.channel_set.freq); if ((new_idx >= 0 && new_idx != conf.intf.channel_idx) || conf.intf.channel_set.width != conf.intf.channel.width || set_ht40plus != <API key>(&conf.intf.channel)) { conf.intf.channel_set.center_freq = conf.intf.channel_set.freq + (set_ht40plus ? 10 : -10); /* some setting changed */ if (conf.serveraddr[0] == '\0') { /* server */ if (!<API key>(&conf.intf, &conf.intf.channel_set)) { /* reset UI */ conf.intf.channel_set = conf.intf.channel; } else { <API key>(); } } else { /* client */ conf.intf.channel_idx = new_idx; conf.intf.channel = conf.intf.channel_set; printlog(LOG_INFO, "Sending channel config to server"); <API key>(); } } return false; default: return false; /* didn't handle input */ } update_channel_win(win); return true; }
<div class="tile is-parent is-vertical"> <div *ngFor="let location of locations" [ngClass]="{'tile': true, 'is-child': true, 'box': true, 'notification': true, 'is-success': !location.currentLocation && location.canTravelHere, 'is-danger': !location.currentLocation && !location.canTravelHere}"> <app-location [location]="location"></app-location> </div> </div>
# CRuMb A very small, lightweight CRM for the Beer industry
Exuberant Ctags ============ Author: Darren Hiebert <dhiebert at users.sourceforge.net> http://ctags.sourceforge.net Instant Messaging: Yahoo! ID : dbhiebert AIM ScreenName: darrenhiebert Exuberant Ctags is a multilanguage reimplementation of the much-underused ctags(1) program and is intended to be the mother of all ctags programs. It generates indexes of source code definitions which are used by a number of editors and tools. The motivation which drove the development of Exuberant Ctags was the need for a ctags program which supported generation of tags for all possible C language constructs (which no other ctags offers), and because most were easily fooled by a number of preprocessor contructs. Exuberant Ctags offers the following features: 1. It supports the following languages: Assembler, AWK, ASP, BETA, Bourne/Korn/Z Shell, C, C++, C#, COBOL, Eiffel, Erlang, Elixir, Fortran, Go, Java, Lisp, Lua, Makefile, Pascal, Perl, PHP, PL/SQL, Python, REXX, Ruby, Scheme, S-Lang, SML (Standard ML), Tcl, Vera, Verilog, VHDL, Vim, and YACC. 2. It is capable of generating tags for virtually all C language constructs. 3. It is very robust in parsing code. In particular, the C/C++ parser is far less easily fooled by code containing #if preprocessor conditional constructs, using a conditional path selection algorithm to resolve complicated situations, and a fall-back algorithm when this one fails. 4. Supports output of Emacs-style TAGS files (i.e. "etags"). 5. User-defined languages, using Posix regular expressions. 6. Supports UNIX, MSDOS, Windows 95/98/NT/2000/XP, OS/2, QNX, Amiga, QDOS, RISC OS, VMS, Macintosh, and Cray. Some pre-compiled binaries are available on the web site. Visit the Exuberant Ctags web site: http://ctags.sourceforge.net Which brings us to the most obvious question: Q: Why is it called "Exuberant" ctags? A: Because one of the meanings of the word is: exuberant : produced in extreme abundance : PLENTIFUL syn see PROFUSE Compare the tag file produced by Exuberant Ctags with that produced by any other ctags and you will see how appropriate the name is. This source code is distributed according to the terms of the GNU General Public License. It is provided on an as-is basis and no responsibility is accepted for its failure to perform as expected. It is worth at least as much as you paid for it! Exuberant Ctags was originally derived from and inspired by the ctags program by Steve Kirkendall (kirkenda@cs.pdx.edu) that comes with the Elvis vi clone (though almost none of the original code remains). This, too, is freely available. Please report any problems you find. The two problems I expect to be most likely are either a tag which you expected but is missing, or a tag created in error (shouldn't really be a tag). Please include a sample of code (the definition) for the object which misbehaves. vim:tw=76:sw=4:et:
<?php defined( '_JEXEC' ) or die; defined('JPATH_PLATFORM') or die; jimport('joomla.form.formfield'); jimport('joomla.form.helper'); JFormHelper::loadFieldClass('list'); class <API key> extends JFormFieldList { protected $type = 'ToolbarList'; protected function getOptions() { $options = array(); $items = ARKHelper::getEditorToolbars(); // Build the field options. if(!empty($items)) { foreach($items as $item) { $options[] = JHtml::_( 'select.option', $item, $item ); } } // Merge any additional options in the XML definition. $options = array_merge(parent::getOptions(), $options); return $options; } }
<?php require_once ('define_upsell.php'); $lg_conv = array(2 => 'fr', 3 => 'sp', 4 => 'de', 5 => 'en', 6 => 'it', 7 => 'pl'); $product = $_GET['upsell']; $lg_code = $_SESSION['languages_id']; $lg_code = $lg_conv[$lg_code]; echo ' <div id="km"> <div id="km_content">'; //var_dump($productTab[$product]); // Template pour le type Premium if ($product == 'premium') { echo' <ul id="km_title"> <li><h1 class="km_titre_1">'.$productTab[$product]['productName'][$lg_code].'</h1></li> <li><h1 class="km_titre_1">'.$productTab[$product]['title'][$lg_code].'</h1></li> </ul> <div id="km_left"> <ul> <li class="km_price_rouge">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; '.getDevise($_SESSION['languages_id']).' '.$productTab[$product]['price'].'&nbsp;&nbsp;&nbsp;<br></li> <li><a href="index.php?main_page=index&action=buy_now&products_id='.$productTab[$product]['productId'].'"><img id="imgbuynow" alt="'.$productTab['buyNow'][$lg_code].'" src="upsell/images/buy_'.$lg_code.'.gif"/></a></li> <li class="km_videoprojecteur" style="padding-left:65px;"> <img src="upsell/images/pastille_garantie_'.$_SESSION['languages_id'].'.jpg" width="150" height="156" alt="'.$productTab['premium']['altPic']['fr'].'" /></li> <li class="km_texte_prem"><span class="km_texte_premnoir">'.$productTab[$product]['longDesc'][$lg_code][1].'</li> </ul> </div> <div id="km_right"> <ul> <li class="km_texte_prem_right">'.$productTab[$product]['longDesc'][$lg_code][2].'</li> </ul> </div>'; } else { // Template pour le type sp200, dust-go etc. echo ' <ul id="km_title"> <li><h1 class="km_titre_1">'.$productTab[$product]['productName'].'</h1></li> <li><h1 class="km_titre_1">'.$productTab[$product]['title'][$lg_code].'</h1></li> </ul> <div id="km_left"> <ul> <li><img src="upsell/images/'.$productTab[$product]['img'].'" width="275" height="275" alt="sp400" class="km_image"/></li> <li class="km_cliquez">'.$productTab['seeOther'][$lg_code].'</li> <li> <div id="km_vignette"> <ul>'; for ($i = 1; $i <=6; $i++) { echo '<li><a href="upsell/images/'.$productTab[$product]['imgOther'.$i.''].'" rel="lightbox[galerie]"><img src="upsell/images/'.substr($productTab[$product]['imgOther'.$i.''], 0, -4).'_v.jpg" width="42" height="42" alt="'.$product.'" class="km_vignette" /></a></li>'; } echo ' </ul></div> </li> <li class="km_question">'.$productTab['question'][$lg_code].'<br />'.$productTab['contact'][$lg_code].'</li> </ul> </div> <div id="km_right"> <ul> <li class="km_détailsCopie" style="font-weight: bold;font-size: 1.5em;color: rgb(255, 221, 138);">'.$productTab['desc'][$lg_code].' </li>'; $nbrEntre = sizeof($productTab[$product]['longDesc'][$lg_code]); for($i = 1; $i <= $nbrEntre; $i++) { echo '<li class="km_texte_courant">'.$productTab[$product]['longDesc'][$lg_code][$i].'</li>'; } echo ' <li class="km_texte_courant"> <br /> <font style="font-size: 3em;color: rgb(255, 105, 0);">€&nbsp;'.$productTab[$product]['price'].'</font> &nbsp;&nbsp;'; if ($productTab[$product]['price'] != '219' AND $productTab[$product]['price'] != '699') { echo '<span style="text-decoration:line-through;">€&nbsp;'.$productTab[$product]['priceOld'].'</span>'; } echo ' &nbsp; &nbsp; &nbsp; <img src=includes/templates/template_default/images/'.$lg_code.'/in_stock2.gif>&nbsp; &nbsp; &nbsp;&nbsp; &nbsp;&nbsp; <a href="index.php?main_page=index&action=buy_now&products_id='.$productTab[$product]['productId'].'"><img id="imgbuynow" alt="'.$productTab['buyNow'][$lg_code].'" src="upsell/images/buy_'.$lg_code.'.gif"/></a> <br /> <br /> <br /> <li class="km_détailsCopie" style="font-weight: bold;font-size: 1.5em;color: rgb(255, 221, 138);">'.$productTab[$product]['dTech'][$lg_code].'</li>'; $nbreCond = sizeof($productTab[$product]['condition'][$lg_code]); for ($i = 1; $i <= $nbreCond; $i++) { echo '<li class="km_texte_courant">'.$productTab[$product]['condition'][$lg_code][$i].'</li>'; } echo '</ul> </div>'; } echo '</div></div>'; ?>
#include "jeeps/gps.h" #include <cfloat> #include <cstdio> #include <cstdlib> int32 GPS_Command_Off(const char* port) { static UC data[2]; gpsdevh* fd; GPS_PPacket tra; GPS_PPacket rec; GPS_Util_Little(); if (!GPS_Device_On(port, &fd)) { return gps_errno; } GPS_Util_Put_Short(data,COMMAND_ID[gps_device_command].Cmnd_Turn_Off_Pwr); /* robertl - LINK_ID isn't set yet. Hardcode it to Garmin spec value */ GPS_Make_Packet(&tra, 10, /* LINK_ID[gps_link_type].Pid_Command_Data, */ data,2); if (!GPS_Write_Packet(fd,tra)) { return gps_errno; } if (!<API key>(fd)) { if (!GPS_Get_Ack(fd, &tra, &rec)) { return gps_errno; } GPS_User("Power off command acknowledged"); } if (!GPS_Device_Off(fd)) { return gps_errno; } return 1; } int32 <API key>(const char* port, GPS_PWay** way, pcb_fn cb) { int32 ret=0; /* * It's a bit tacky to do this up front without ticking the * progress meter, but this come in pretty quickly... */ if (<API key>) { ret = GPS_A101_Get(port); if (!ret) { fatal("blah"); return PROTOCOL_ERROR; } } switch (gps_waypt_transfer) { case pA100: ret = GPS_A100_Get(port,way, cb); break; default: GPS_Error("Get_Waypoint: Unknown waypoint protocol"); return PROTOCOL_ERROR; } return ret; } int32 <API key>(const char* port, GPS_PWay* way, int32 n, int (*cb)(struct GPS_SWay**)) { int32 ret=0; switch (gps_waypt_transfer) { case pA100: ret = GPS_A100_Send(port, way, n, cb); break; default: GPS_Error("Send_Waypoint: Unknown waypoint protocol"); return PROTOCOL_ERROR; } return ret; } int32 <API key>(const char* port, GPS_PWay** way) { int32 ret=0; switch (gps_route_transfer) { case pA200: ret = GPS_A200_Get(port,way); break; case pA201: ret = GPS_A201_Get(port,way); break; default: GPS_Error("Get_Route: Unknown route protocol"); return PROTOCOL_ERROR; } return ret; } int32 <API key>(const char* port, GPS_PWay* way, int32 n) { int32 ret=0; switch (gps_route_transfer) { case pA200: ret = GPS_A200_Send(port, way, n); break; case pA201: ret = GPS_A201_Send(port, way, n); break; default: GPS_Error("Send_Route: Unknown route protocol"); return PROTOCOL_ERROR; } return ret; } int32 <API key>(const char* port, GPS_PTrack** trk, pcb_fn cb) { int32 ret=0; if (gps_trk_transfer == -1) { return GPS_UNSUPPORTED; } switch (gps_trk_transfer) { case pA300: ret = GPS_A300_Get(port,trk,cb); break; case pA301: case pA302: ret = GPS_A301_Get(port,trk,cb,301); break; default: GPS_Error("Get_Track: Unknown track protocol %d\n", gps_trk_transfer); return PROTOCOL_ERROR; } return ret; } int32 <API key>(const char* port, GPS_PTrack* trk, int32 n, int eraset) { int32 ret=0; if (gps_trk_transfer == -1) { return GPS_UNSUPPORTED; } switch (gps_trk_transfer) { case pA300: ret = GPS_A300_Send(port, trk, n); break; case pA301: ret = GPS_A301_Send(port, trk, n, 301, nullptr); break; case pA302: /* Units with A302 don't support track upload, so we convert the * track to a course on the fly and send that instead */ ret = <API key>(port, trk, n, nullptr, 0, eraset); break; default: GPS_Error("Send_Track: Unknown track protocol %d.", gps_trk_transfer); break; } return ret; } int32 <API key>(const char* port, GPS_PWay** way) { int32 ret=0; if (<API key> == -1) { return GPS_UNSUPPORTED; } switch (<API key>) { case pA400: ret = GPS_A400_Get(port,way); break; default: GPS_Error("Get_Proximity: Unknown proximity protocol"); return PROTOCOL_ERROR; } return ret; } int32 <API key>(const char* port, GPS_PWay* way, int32 n) { int32 ret=0; if (<API key> == -1) { return GPS_UNSUPPORTED; } switch (<API key>) { case pA400: ret = GPS_A400_Send(port, way, n); break; default: GPS_Error("Send_Proximity: Unknown proximity protocol"); break; } return ret; } int32 <API key>(const char* port, GPS_PAlmanac** alm) { int32 ret=0; if (<API key> == -1) { return GPS_UNSUPPORTED; } switch (<API key>) { case pA500: ret = GPS_A500_Get(port,alm); break; default: GPS_Error("Get_Almanac: Unknown almanac protocol"); return PROTOCOL_ERROR; } return ret; } int32 <API key>(const char* port, GPS_PAlmanac* alm, int32 n) { int32 ret=0; if (<API key> == -1) { return GPS_UNSUPPORTED; } switch (<API key>) { case pA500: ret = GPS_A500_Send(port, alm, n); break; default: GPS_Error("Send_Almanac: Unknown almanac protocol"); break; } return ret; } time_t <API key>(const char* port) { time_t ret=0; switch (<API key>) { case pA600: ret = GPS_A600_Get(port); break; /* * If the unit doesn't support it (i.e. a C320 in charging mode), * but don't treat as error; return as zero. */ case -1: return 0; default: GPS_Error("Get_Time: Unknown date/time protocol"); return PROTOCOL_ERROR; } return ret; } int32 <API key>(const char* port, time_t Time) { time_t ret=0; switch (<API key>) { case pA600: ret = GPS_A600_Send(port, Time); break; default: GPS_Error("Send_Time: Unknown date/time protocol"); return PROTOCOL_ERROR; } return ret; } int32 <API key>(const char* port, double* lat, double* lon) { int32 ret=0; switch (<API key>) { case pA700: ret = GPS_A700_Get(port,lat,lon); break; /* * If the unit doesn't support it (i.e. a C320 in charging mode), * zero lat/lon, but don't treat as error. */ case -1: *lat = *lon = 0.0; break; default: GPS_Error("Get_Position: Unknown position protocol"); return PROTOCOL_ERROR; } return ret; } int32 <API key>(const char* port, double lat, double lon) { int32 ret=0; switch (<API key>) { case pA700: ret = GPS_A700_Send(port, lat, lon); break; default: GPS_Error("Send_Position: Unknown position protocol"); return PROTOCOL_ERROR; } return ret; } int32 GPS_Command_Pvt_On(const char* port, gpsdevh** fd) { int32 ret=0; if (gps_pvt_transfer == -1) { return GPS_UNSUPPORTED; } switch (gps_pvt_transfer) { case pA800: ret = GPS_A800_On(port,fd); break; default: GPS_Error("Pvt_On: Unknown position protocol"); return PROTOCOL_ERROR; } return ret; } int32 GPS_Command_Pvt_Off(const char* port, gpsdevh** fd) { int32 ret=0; if (gps_pvt_transfer == -1) { return GPS_UNSUPPORTED; } switch (gps_pvt_transfer) { case pA800: ret = GPS_A800_Off(port,fd); break; default: GPS_Error("Pvt_Off: Unknown position protocol"); return PROTOCOL_ERROR; } return ret; } int32 GPS_Command_Pvt_Get(gpsdevh** fd, GPS_PPvt_Data* pvt) { int32 ret=0; if (gps_pvt_transfer == -1) { return GPS_UNSUPPORTED; } (*pvt)->fix = 0; switch (gps_pvt_transfer) { case pA800: ret = GPS_A800_Get(fd,pvt); break; default: GPS_Error("Pvt_Get: Unknown position protocol"); return PROTOCOL_ERROR; } return ret; } int32 GPS_Command_Get_Lap(const char* port, GPS_PLap** lap, pcb_fn cb) { int32 ret=0; if (gps_lap_transfer == -1) { return GPS_UNSUPPORTED; } switch (gps_lap_transfer) { case pA906: ret = GPS_A906_Get(port,lap, cb); break; default: GPS_Error("Get_Lap: Unknown lap protocol"); return PROTOCOL_ERROR; } return ret; } int32 <API key> (const char* port, GPS_PCourse** crs, GPS_PCourse_Lap** clp, GPS_PTrack** trk, GPS_PCourse_Point** cpt, int32* n_clp, int32* n_trk, int32* n_cpt, pcb_fn cb) { int32 ret=0; if (gps_course_transfer == -1) { return GPS_UNSUPPORTED; } switch (gps_course_transfer) { case pA1006: ret = GPS_A1006_Get(port,crs,cb); break; default: GPS_Error("Get_Course: Unknown course protocol"); return PROTOCOL_ERROR; } switch (<API key>) { case pA1007: *n_clp = GPS_A1007_Get(port,clp, nullptr); break; default: GPS_Error("Get_Course: Unknown course lap protocol"); return PROTOCOL_ERROR; } switch (<API key>) { case pA1012: GPS_Error("Get_Course: Not implemented track protocol %d\n", gps_trk_transfer); break; case pA302: *n_trk = GPS_A301_Get(port,trk,cb,302); break; default: GPS_Error("Get_Course: Unknown course track protocol %d\n", gps_trk_transfer); return PROTOCOL_ERROR; } switch (<API key>) { case pA1008: *n_cpt = GPS_A1008_Get(port,cpt, nullptr); break; default: GPS_Error("Get_Course: Unknown course point protocol"); return PROTOCOL_ERROR; } return ret; } int32 <API key> (const char* port, GPS_PCourse* crs, GPS_PCourse_Lap* clp, GPS_PTrack* trk, GPS_PCourse_Point* cpt, int32 n_crs, int32 n_clp, int32 n_trk, int32 n_cpt) { gpsdevh* fd; GPS_OCourse_Limits limits; int32 ret; int32 ret_crs=0; int32 ret_clp=0; int32 ret_trk=0; int32 ret_cpt=0; if (gps_course_transfer == -1 || <API key> == -1) { return GPS_UNSUPPORTED; } /* Check course limits to make sure we're not exceeding the device's * capacity. */ switch (<API key>) { case pA1009: ret = GPS_A1009_Get(port,&limits); Q_UNUSED(ret); break; default: GPS_Error("Send_Course: Unknown course limitsprotocol"); return PROTOCOL_ERROR; } if (n_crs > limits.max_courses || n_clp > limits.max_course_laps || n_trk > limits.max_course_trk_pnt || n_cpt > limits.max_course_pnt) { GPS_Error("Course upload would exceed device capacity:"); GPS_Error("# of courses: %d, max: %d", n_crs, limits.max_courses); GPS_Error("# of laps: %d, max: %d", n_clp, limits.max_course_laps); GPS_Error("# of track points: %d, max: %d", n_trk, limits.max_course_trk_pnt); GPS_Error("# of course points: %d, max: %d", n_cpt, limits.max_course_pnt); return GPS_UNSUPPORTED; } /* Initialize device communication: * In contrast to other transfer protocols, this has to be handled here; * shutting off communication in between the different parts * could lead to data corruption on the device because all the courses * and their associated lap and track data have to be sent in one * transaction. */ if (!GPS_Device_On(port,&fd)) { return gps_errno; } switch (gps_course_transfer) { case pA1006: ret_crs = GPS_A1006_Send(port,crs,n_crs,fd); break; default: GPS_Error("Send_Course: Unknown course protocol"); return PROTOCOL_ERROR; } switch (<API key>) { case pA1007: ret_clp = GPS_A1007_Send(port,clp,n_clp,fd); break; default: GPS_Error("Send_Course: Unknown course lap protocol"); return PROTOCOL_ERROR; } switch (<API key>) { case pA1012: GPS_Error("Send_Course: Not implemented track protocol %d\n", gps_trk_transfer); break; case pA302: ret_trk = GPS_A301_Send(port,trk,n_trk,302,fd); break; default: GPS_Error("Send_Course: Unknown course track protocol %d\n", gps_trk_transfer); return PROTOCOL_ERROR; } switch (<API key>) { case pA1008: ret_cpt = GPS_A1008_Send(port,cpt,n_cpt,fd); break; default: GPS_Error("Send_Course: Unknown course point protocol"); return PROTOCOL_ERROR; } if (!GPS_Device_Off(fd)) { return gps_errno; } return ret_crs * ret_clp * ret_trk * ret_cpt; } static uint32 Unique_Course_Index(GPS_PCourse* crs, int n_crs) { uint32 idx; int i; for (idx=0; ; idx++) { for (i=0; i<n_crs; i++) if (crs[i]->index==idx) { break; /* Already have this index */ } if (i>=n_crs) { return idx; /* Found unused index */ } } } static uint32 Unique_Track_Index(GPS_PCourse* crs, int n_crs) { uint32 idx; int i; for (idx=0; ; idx++) { for (i=0; i<n_crs; i++) if (crs[i]->track_index==idx) { break; /* Already have this index */ } if (i>=n_crs) { return idx; /* Found unused index */ } } } static void <API key>(GPS_PCourse_Lap clp, GPS_PTrack* ctk, int ctk_start, int ctk_end) { int i; double heartrate_sum = 0, cadence_sum = 0; int heartrate_sum_time = 0, cadence_sum_time = 0; double time_synth_speed = 10.0 * 1000 / 3600; /* speed in m/s */ if (ctk_start && ctk_end && !ctk[ctk_start]->Time) { ctk[ctk_start]->Time = GPS_Time_Now(); } else { time_synth_speed = 0; } clp->total_dist = 0; clp->avg_heart_rate = 0; clp->max_heart_rate = 0; clp->intensity = 0; clp->avg_cadence = 0xff; for (i=ctk_start; i <= ctk_end; i++) { if (ctk[i]->heartrate && ctk[i]->heartrate > clp->max_heart_rate) { clp->max_heart_rate = ctk[i]->heartrate; } if (i < ctk_end) { double dist = 0; int seg_time; if (!ctk[i]->no_latlon && !ctk[i+1]->no_latlon) dist = gcgeodist(ctk[i]->lat, ctk[i]->lon, ctk[i+1]->lat, ctk[i+1]->lon); clp->total_dist += dist; if (time_synth_speed) { ctk[i+1]->Time = ctk[i]->Time + (dist / time_synth_speed + 0.5); } seg_time = ctk[i+1]->Time - ctk[i]->Time; if (ctk[i]->heartrate) { heartrate_sum += ctk[i]->heartrate * seg_time; heartrate_sum_time += seg_time; } if (ctk[i]->cadence) { cadence_sum += ctk[i]->cadence * seg_time; cadence_sum_time += seg_time; } } } clp->total_time = 0; clp->begin_lat = 0x7fffffff; clp->begin_lon = 0x7fffffff; clp->end_lat = 0x7fffffff; clp->end_lon = 0x7fffffff; if (ctk_start && ctk_end) { clp->total_time = (ctk[ctk_end]->Time - ctk[ctk_start]->Time) * 100; if (!ctk[ctk_start]->no_latlon && !ctk[ctk_end]->no_latlon) { clp->begin_lat = ctk[ctk_start]->lat; clp->begin_lon = ctk[ctk_start]->lon; clp->end_lat = ctk[ctk_end]->lat; clp->end_lon = ctk[ctk_end]->lon; } } if (heartrate_sum_time) { clp->avg_heart_rate = heartrate_sum / heartrate_sum_time; } if (cadence_sum_time) { clp->avg_cadence = cadence_sum / cadence_sum_time; } } static void <API key>(GPS_PCourse* crs, int* n_crs, GPS_PCourse_Lap* clp, int* n_clp, GPS_PTrack* ctk, int* n_ctk, GPS_PCourse_Point* cpt, int* n_cpt) { int i, j; /* Remove courses with duplicate names, keeping newest. * This is actually pretty important: Sending two courses with the same * name to the device will result in internal data corruption on the * device (e.g. "inventing" laps with weird course IDs that nobody ever * transferred to it, that change with every upload of unrelated data * and that can't be deleted except with a master reset by holding the * Mode button during power on). */ restart_courses: for (i=*n_crs-1; i>0; i for (j=i-1; j>=0; j if (!strcmp(crs[i]->course_name, crs[j]->course_name)) { /* Remove course */ GPS_Course_Del(&crs[j]); memmove(&crs[j], &crs[j+1], (*n_crs-j-1)*sizeof(*crs)); (*n_crs) goto restart_courses; } } } /* Remove unreferenced laps */ restart_laps: for (i=0; i<*n_clp; i++) { for (j=0; j<*n_crs; j++) if (crs[j]->index == clp[i]->course_index) { break; } if (j>=*n_crs) { /* Remove lap */ GPS_Course_Lap_Del(&clp[i]); memmove(&clp[i], &clp[i+1], (*n_clp-i-1)*sizeof(*clp)); (*n_clp) goto restart_laps; } } /* Remove unreferenced tracks */ restart_tracks: for (i=0; i<*n_ctk; i++) { uint32 trk_idx; if (!ctk[i]->ishdr) { continue; } trk_idx = strtoul(ctk[i]->trk_ident, nullptr, 0); for (j=0; j<*n_crs; j++) if (crs[j]->track_index == trk_idx) { break; } if (j>=*n_crs) { /* Remove track */ for (j=i; j<*n_ctk; j++) { if (j!=i && ctk[j]->ishdr) { break; } GPS_Track_Del(&ctk[j]); } memmove(&ctk[i], &ctk[j], (*n_ctk-j)*sizeof(*ctk)); *(n_ctk) -= j-i; goto restart_tracks; } } /* Remove unreferenced/duplicate course points */ <API key>: for (i=0; i<*n_cpt; i++) { /* Check for unreferenced point */ for (j=0; j<*n_crs; j++) if (crs[j]->index == cpt[i]->course_index) { break; } if (j<*n_crs) { /* Check for duplicate point */ for (j=0; j<i; j++) if (cpt[i]->course_index == cpt[j]->course_index && cpt[i]->track_point_time == cpt[j]->track_point_time) { break; } if (j>=i) { continue; /* Referenced & unique */ } } /* Remove course point */ <API key>(&cpt[i]); memmove(&cpt[i], &cpt[i+1], (*n_cpt-i-1)*sizeof(*cpt)); (*n_cpt) goto <API key>; } } int32 <API key>(const char* port, GPS_PTrack* trk, int32 n_trk, GPS_PWay* wpt, int32 n_wpt, int eraset) { GPS_PCourse* crs = nullptr; GPS_PCourse_Lap* clp = nullptr; GPS_PTrack* ctk = nullptr; GPS_PCourse_Point* cpt = nullptr; int n_crs, n_clp=0, n_ctk=0, n_cpt=0; int i, j, trk_end, new_crs, first_new_ctk; int32 ret; /* Read existing courses from device */ if (eraset) { n_crs = 0; } else { n_crs = <API key>(port, &crs, &clp, &ctk, &cpt, &n_clp, &n_ctk, &n_cpt, nullptr); if (n_crs < 0) { return n_crs; } } /* Create new course+lap+track points for each track */ new_crs = n_crs; for (i=0; i<n_trk; i++) { if (!trk[i]->ishdr) { continue; } /* Find end of track */ for (trk_end=i; trk_end<n_trk-1; trk_end++) if (trk[trk_end+1]->ishdr) { break; } if (trk_end==i) { continue; /* Skip empty track */ } /* Create & append course */ crs = (struct GPS_SCourse**)xrealloc(crs, (n_crs+1) * sizeof(GPS_PCourse)); crs[n_crs] = GPS_Course_New(); if (!crs[n_crs]) { if (clp) xfree(clp); return MEMORY_ERROR; } crs[n_crs]->index = Unique_Course_Index(crs, n_crs); strncpy(crs[n_crs]->course_name, trk[i]->trk_ident, sizeof(crs[n_crs]->course_name)-1); crs[n_crs]->track_index = Unique_Track_Index(crs, n_crs); /* Create & append new lap */ clp = (struct GPS_SCourse_Lap**) xrealloc(clp, (n_clp+1) * sizeof(GPS_PCourse_Lap)); clp[n_clp] = GPS_Course_Lap_New(); if (!clp[n_clp]) { if (clp) xfree(clp); return MEMORY_ERROR; } clp[n_clp]->course_index = crs[n_crs]->index; /* Index of associated course */ clp[n_clp]->lap_index = 0; /* Lap index, unique per course */ <API key>(clp[n_clp], trk, i+1, trk_end); n_crs++; n_clp++; } /* Append new track points */ ctk = (struct GPS_STrack**) xrealloc(ctk, (n_ctk+n_trk) * sizeof(GPS_PTrack)); first_new_ctk = n_ctk; for (i=0; i<n_trk; i++) { if (trk[i]->ishdr && (i>=n_trk || trk[i+1]->ishdr)) { continue; } ctk[n_ctk] = GPS_Track_New(); if (!ctk[n_ctk]) { if (clp) xfree(clp); return MEMORY_ERROR; } *ctk[n_ctk] = *trk[i]; if (trk[i]->ishdr) { /* Index of new track, must match the track index in associated course */ memset(ctk[n_ctk]->trk_ident, 0, sizeof(ctk[n_ctk]->trk_ident)); sprintf(ctk[n_ctk]->trk_ident, "%u", crs[new_crs]->track_index); new_crs++; } n_ctk++; } /* Convert waypoints to course points by searching closest track point & * append */ cpt = (struct GPS_SCourse_Point**) xrealloc(cpt, (n_cpt+n_wpt) * sizeof(GPS_PCourse_Point)); for (i=0; i<n_wpt; i++) { double dist, min_dist = DBL_MAX; uint32 min_dist_idx = 0, trk_idx = 0, min_dist_trk_idx = 0; /* Find closest track point */ for (j=first_new_ctk; j<n_ctk; j++) { if (ctk[j]->ishdr) { trk_idx = strtoul(ctk[j]->trk_ident, nullptr, 0); continue; } if (wpt[i] == nullptr || ctk[j] == nullptr) { fatal("Internal error in <API key>"); } dist = gcgeodist(wpt[i]->lat, wpt[i]->lon, ctk[j]->lat, ctk[j]->lon); if (dist < min_dist) { min_dist = dist; min_dist_idx = j; min_dist_trk_idx = trk_idx; } } if (wpt[i] == nullptr) { fatal("Internal error in <API key>: no wpt"); } cpt[i+n_cpt] = <API key>(); strncpy(cpt[i+n_cpt]->name, wpt[i]->cmnt, sizeof(cpt[i+n_cpt]->name) - 1); for (j=0; j<n_crs; j++) if (crs[j]->track_index == min_dist_trk_idx) { cpt[i+n_cpt]->course_index = crs[j]->index; break; } cpt[i+n_cpt]->track_point_time = ctk[min_dist_idx]->Time; cpt[i+n_cpt]->point_type = 0; } n_cpt += n_wpt; /* Remove course data that's no longer needed */ <API key>(crs, &n_crs, clp, &n_clp, ctk, &n_ctk, cpt, &n_cpt); /* Finally send courses including new ones to device */ ret = <API key>(port, crs, clp, ctk, cpt, n_crs, n_clp, n_ctk, n_cpt); for (i=0; i<n_crs; i++) { GPS_Course_Del(&crs[i]); } free(crs); for (i=0; i<n_clp; i++) { GPS_Course_Lap_Del(&clp[i]); } free(clp); for (i=0; i<n_ctk; i++) { GPS_Track_Del(&ctk[i]); } free(ctk); for (i=0; i<n_cpt; i++) { <API key>(&cpt[i]); } free(cpt); return ret; } /*Stubs for unimplemented stuff*/ int32 <API key>(const char* /* port */, void** /* lap */, int (* /* cb */)(int, struct GPS_SWay**)) { return 0; } int32 <API key>(const char* /* port */, void** /* lap */, int (* /* cb */)(int, struct GPS_SWay**)) { return 0; } int32 <API key>(const char* /* port */, void** /* lap */, int (* /* cb */)(int, struct GPS_SWay**)) { return 0; } int32 <API key>(const char* /* port */, void** /* lap */, int (* /* cb */)(int, struct GPS_SWay**)) { return 0; }
<?php /** * Exception for errors with the PList format * @author Rodney Rehm <rodney.rehm@medialize.de> * @author Christian Kruse <cjk@wwwtech.de> * @package plist */ class PListException extends Exception { } ?>
package java8.util.function; import java8.util.function.UnaryOperator; /** * Represents an operation on a single {@code long}-valued operand that produces * a {@code long}-valued result. This is the primitive type specialization of * {@link UnaryOperator} for {@code long}. * * <p>This is a <a href="package-summary.html">functional interface</a> * whose functional method is {@link #applyAsLong(long)}. * * @see UnaryOperator * @since 1.8 */ public interface LongUnaryOperator { /** * Applies this operator to the given operand. * * @param operand the operand * @return the operator result */ long applyAsLong(long operand); }
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/PhotoLibrary.framework/PhotoLibrary */ #import <PhotoLibrary/<API key>.h> #import <PhotoLibrary/XXUnknownSuperclass.h> @class <API key>, <API key>, UIView, <API key>, PLCameraFocusView; @interface PLCameraPreviewView : XXUnknownSuperclass { CGPoint _touchLocation; // 48 = 0x30 <API key> *_focusView; // 56 = 0x38 PLCameraFocusView *_autoFocusView; // 60 = 0x3c <API key> *_lockFocusView; // 64 = 0x40 <API key> *_faceDetectionView; // 68 = 0x44 UIView *_disabledView; // 72 = 0x48 UIView *_snapshotView; // 76 = 0x4c unsigned _canShowFocus : 1; // 80 = 0x50 unsigned _controlsAreVisible : 1; // 80 = 0x50 } + (CGAffineTransform)<API key>; // 0xc6f45 - (void)<API key>:(CGRect)rect; // 0xc7cc9 - (void)<API key>:(BOOL)visible; // 0xc7c01 - (void)setShouldShowFocus:(BOOL)showFocus; // 0xc7bb9 - (void)focusDidEnd; // 0xc7b55 - (void)showAutofocusView; // 0xc78f9 - (void)removeFocusView; // 0xc7851 - (void)dealloc; // 0xc775d - (void)<API key>:(BOOL)modes; // 0xc74cd - (void)motionEnded:(int)ended withEvent:(id)event; // 0xc74a5 - (void)zoomFromFactor:(float)factor toFactor:(float)factor2 transform:(CGAffineTransform)transform; // 0xc73a5 - (void)<API key>; // 0xc7385 - (void)animateFocusLock; // 0xc7365 - (void)<API key>:(CGPoint)point; // 0xc7179 - (void)showFocusAtPoint:(CGPoint)point; // 0xc6f8d - (id)initWithFrame:(CGRect)frame; // 0xc6eb9 @end
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/OfficeImport.framework/OfficeImport */ #import <OfficeImport/<API key>.h> #import <OfficeImport/NSCopying.h> #import <OfficeImport/XXUnknownSuperclass.h> __attribute__((visibility("hidden"))) @interface OADVector3D : XXUnknownSuperclass <NSCopying> { @private float mDx; // 4 = 0x4 float mDy; // 8 = 0x8 float mDz; // 12 = 0xc } - (id)initWithDx:(float)dx dy:(float)dy dz:(float)dz; // 0x29c9c9 - (float)dx; // 0x29c5b1 - (float)dy; // 0x29c5c1 - (float)dz; // 0x29c5d1 - (id)copyWithZone:(NSZone *)zone; // 0x29c85d - (unsigned)hash; // 0x29c5e1 - (BOOL)isEqual:(id)equal; // 0x29c8d9 @end
# This file is part of GNU Enterprise. # GNU Enterprise is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public # version 2, or (at your option) any later version. # GNU Enterprise is distributed in the hope that it will be # You should have received a copy of the GNU General Public # write to the Free Software Foundation, Inc., 59 Temple Place # - Suite 330, Boston, MA 02111-1307, USA. # FILE: # GFTree.py # DESCRIPTION: """ Logical tree support TODO: completely remove row from uiObject interface, replace with id """ import re import itertools import datetime from GFTabStop import GFTabStop from toolib import debug from GFStyles import GFStyles from gnue.common.datasources.access import ACCESS REC_FIELD = re.compile(r"\%(\([A-Za-z_]\w*\))") DEBUG=0 class GFTreeMixIn(object): # Constructor def __init__(self): # default attribute values self.rootname = None # will be definded in phase 1 init self._rootId = None self.__nodeNameFields = None self.__nodeNamePattern = None # filled in phase 1 init self._fldId = None self._fldParent = None # filled on event self._rs = None # tree data self.__childIds = {} self._idRow = {} self._structureChanged = False self.__nodeStyles = None # state fix self.<API key> = False # triggers self._validTriggers = { 'PRE-FOCUSOUT' : 'Pre-FocusOut', 'POST-FOCUSOUT' : 'Post-FocusOut', 'PRE-FOCUSIN' : 'Pre-FocusIn', 'POST-FOCUSIN' : 'Post-FocusIn', 'ON-NEXT-ENTRY' : 'On-Next-Entry', 'ON-PREVIOUS-ENTRY': 'On-Previous-Entry', 'RECORD-ACTIVATED' : 'Record-Activated', 'RECORD-CHECKED' : 'Record-Checked', 'POST-REFRESH' : 'Post-Refresh', } self._triggerFunctions = { 'getBlock': {'function': lambda: self._block.<API key>()}, 'getCheckedNodesData': {'function': self.<API key>}, #'<API key>': {'function': self.<API key>}, 'getChildNodesData' : {'function': self.<API key>}, 'setChildNodesData' : {'function': self.<API key>}, 'checkAllNodes' : {'function': self.<API key> }, # expose tree model 'getRootId' : {'function': self.getRootId}, 'getChildIds' : {'function': self.iterChildIds}, 'getParentId' : {'function': self.<API key>}, 'getValue' : {'function': self.__trigger_getValue}, 'setValue' : {'function': self.__trigger_setValue}, 'isLeaf' : {'function': self.__trigger_isLeaf}, } self._triggerProperties = { } # Initialisation def _phase_1_init_(self): super(GFTreeMixIn, self)._phase_1_init_() self._rootId = eval(self.rootid, {}) # nodename -> create __nodeNameFields, __nodeNamePattern # substitute %(fieldname)s with %s and add field into list self.__nodeNameFields = [] def sub(m): self.__nodeNameFields.append(m.groups()[0][1:-1]) return '%' self.__nodeNamePattern = REC_FIELD.sub(sub, self.nodename) #rint "nodename fields:", self.__nodeNameFields #rint "nodename pattern:", self.__nodeNamePattern # tree is not GFFieldBound self._block = self.get_block() assert not self._block.autoNextRecord, "Tree block '%s' can't have autoNextRecord='Y'" % self._block.name #translate to resultset field self._fldId = self._rsField(self.fld_id) self._fldParent = self._rsField(self.fld_parent) self._fldStyle = self._rsField(self.fld_style) if getattr(self, 'fld_style', None) else None self._fldsNodeName = map(self._rsField, self.__nodeNameFields) assert self._fldId, 'id field has no field atribute' assert self._fldParent, 'parent field has no field atribute' # Register event handling functions self._block.getDataSource().<API key>({ '<API key>': self.<API key>, # from datasources.GDataSource 'dsResultSetChanged' : self.<API key>, #'dsRecordLoaded' : self.__ds_record_loaded, # from datasources.drivers.Base.Record #'dsRecordInserted' : self.<API key>, # -/- #'dsRecordTouched' : self.__ds_record_touched, # -/- 'dsRecordChanged' : self.__ds_record_changed, 'dsCommitInsert' : self.__ds_commit_insert, #'dsCommitUpdate' : self.__ds_commit_update, # -/- 'dsCommitDelete' : self.__ds_commit_delete, }) self.__nodeStyles = self.findChildOfType('GFStyles') or GFStyles(self) # Validation def _revalidate(self): # internal data validation # self.__childIds is { rowId : [childId1, childId2...]} # self._idRow is { rowId : row } self.__childIds.clear() self._idRow.clear() # if we have virtual root if self.rootname is not None: # root id (virtual) row has index -1 self._idRow[self._rootId] = -1 # children of NotImplemented parent is Virtual Root (row -1) self.__childIds[NotImplemented] = [self._rootId] for row, record in enumerate(self._rs or ()): if not record.isDeleted() and not record.isEmpty(): id = record[self._fldId] self._idRow[id] = row parentId = record[self._fldParent] if id != parentId: self.__childIds.setdefault(parentId, []).append(id) else: debug.error("! Cyclic tree node reference removed", id) if 0: self._dump() self.processTrigger('POST-REFRESH') self.uiWidget._ui_revalidate_() def _dump(self): print " for k, v in self.__childIds.iteritems(): print k, v print " print self._idRow print " def _iterRowsRecursive(self, row, includeSelf=True): if row >= 0 and includeSelf: yield row for id in self.__childIds.get(self._getIdAt(row), ()): for i in self._iterRowsRecursive(self._idRow[id]): yield i # Interface for uiWidget model creation def getRootId(self): if self.rootname is not None: return NotImplemented else: return self._rootId def iterChildIds(self, nodeId): return self.__childIds.get(nodeId, ()) def <API key>(self, nodeId, includeSelf=True): if includeSelf: yield nodeId for i in self.__childIds.get(nodeId, ()): for j in self.<API key>(i, True): yield j def getChildCount(self, id): return len(self.__childIds.get(id, ())) def formatNodeName(self, id): if id != self._rootId: row = self._idRow[id] return (self.__nodeNamePattern % tuple([self.<API key>(row, field) for field in self.__nodeNameFields])).replace('\n', ' ').strip() else: return self.rootname def setNodeName(self, id, text): """ tries to unparse text as in nodeNamePattern and set to fields works only for text fields """ if id is not NotImplemented: row = self._idRow[id] pattern = re.sub(r'(?i)\\\%[^a-z]*[a-z]', lambda m: '(.+)', re.escape(self.__nodeNamePattern)) + '$' m = re.match(pattern, text) if m: for i, text in enumerate(m.groups()): text = text.rstrip() field = self.__nodeNameFields[i] # do not allow to edit primary key if field != self.fld_id: # avoid node revalidation when changing tree label text self.<API key> = True self.<API key>(row, field, text) self.<API key> = False return True return False def isNodeNameEditable(self): """ if tree node name can be updated on existent or new node """ if self.labelEdit: for i in self.__nodeNameFields: if not self._block.getField(i).hasAccess(ACCESS.WRITE): return False return True else: return False def getIdPath(self, id): #rint 'getIdPath', id idPath = [] while id != self.getRootId(): idPath.append(id) #rint 'appended', id try: row = self._idRow[id] except KeyError: #rint "stop via KeyError" break else: if row == -1: id = NotImplemented else: id = self._rs[row][self._fldParent] idPath.reverse() #rint "getIdPath:", idPath return idPath def getNodeStyles(self): return self.__nodeStyles def getNodeStyleKey(self, id): if self._fldStyle: row = self._idRow[id] if row >=0: return self._rs[row][self._fldStyle] else: # virtual root has default style return 'default' else: return 'default' def getNodeStyle(self, id): return self.__nodeStyles.getStyle(self.getNodeStyleKey(id)) # response to events from DataSource def __ds_commit_insert(self, event): if DEBUG: print 'GFTree.commit_insert' self._structureChanged = True def __ds_commit_delete(self, event): if DEBUG: print 'GFTree.commit_delete' self._structureChanged = True def <API key>(self, event): """ - <API key> (parameters: resultSet) whenever the current ResultSet of this datasource changes; this happens when a query is executed or when the master of this datasource moves to another record. - dsResultSetChanged (parameters: resultSet) whenever the current ResultSet has been reloaded from the backend; this happens after each commit if the "requery" option of this datasource is in use. """ if DEBUG: print 'GFTree.resultset_activated', event.resultSet self._rs = event.resultSet self._revalidate() def <API key>(self, event): if DEBUG: print 'GFTree.resultset_changed', self._structureChanged if self._structureChanged: self._revalidate() self._structureChanged = False def __ds_record_changed(self, event): fields = set(event.fields) styleChanged = self._fldStyle is not None and self._fldStyle in fields fields.intersection_update(self._fldsNodeName) nameChanged = not self.<API key> and bool(fields) if nameChanged or styleChanged: id = event.record[self._fldId] if id is not None: self.uiWidget.<API key>(id, nameChanged, styleChanged) # response to events from uiTree def <API key>(self, id): """ node selected with cursor """ try: row = self._idRow[id] except KeyError: debug.error('No row for id: %s' % id) else: # do not select -1 row, it is virtual root #if row >= 0: if row == -1: # usually tree block is editable 'update' so can't do so #self.__block.append_record() #self.__block.last_record() #rint "<API key>, row -1, GO FIRST RECORD" self._block.first_record() else: #rint "<API key>, row", row self._block.goto_record(row) def <API key>(self): """ User doubleckiked node, or pressed enter on node """ self.processTrigger('RECORD-ACTIVATED') self._block.processTrigger('RECORD-ACTIVATED') # internal interface to data def _rsField(self, field): """returns resultset field name by logical field name""" return self._block.getField(field).field def _getIdAt(self, row): if row >= 0: return self._rs[row][self._fldId] else: return self._rootId def _getFieldValueAt(self, row, field): return self._rs[row][self._rsField(field)] def _setFieldValueAt(self, row, field, value): self._rs[row][self._rsField(field)] = value def <API key>(self, row, field): # NOTE: tree has no entries so displayparser is not accessible # TODO: extract display parsing and formatting to GFField # unless can't set values to notext fields value = self._getFieldValueAt(row, field) if value is None: return "" else: field = self._block.getField(field) value = field.lookup(value) # WORKAROUND: since displayHandler in entry we ca't use it for formatting # TODO: formatter must be at field level if field.datatype == 'date' and hasattr(value, 'strftime') or isinstance(value, datetime.date): return value.strftime('%x') elif field.datatype == 'datetime' and hasattr(value, 'strftime') or isinstance(value, datetime.datetime): return value.strftime('%c') else: return unicode(value) def <API key>(self, row, field, text): """ used when setting from clipboard """ # NOTE: tree has no entries so displayparser is not accessible # TODO: extract display parsing and formatting to GFField # unless can't set values to notext fields text = self._block.getField(field).reverse_lookup(text) self._setFieldValueAt(row, field, text or None) # triggers def <API key>(self, fieldnames, reduceChildren=False, style=NotImplemented): data = self._block.get_data(fieldnames) return [ data[self._idRow[id]] for id in self.uiWidget.<API key>(reduceChildren) # TODO: style == self.getNodeStyle(id).name is not good for multiple styles if id is not NotImplemented and id in self._idRow and (style is NotImplemented or style == self.getNodeStyle(id).name) ] #def <API key>(self): # """ # returns True if virtualRoot checked # """ # nodes = self.uiWidget.<API key>(reduceChildren=True) # return None in nodes def <API key>(self, checked=True): self.uiWidget.<API key>(checked) def <API key>(self, fieldnames, id=None, includeSelf=False): data = self._block.get_data(fieldnames) return [data[i] for i in self._iterRowsRecursive( self._idRow[id] if id is not None else self._rs.getRecordNumber(), includeSelf=False )] def <API key>(self, data, id=None, includeSelf=False): """ @param data: { fieldname : valkue, } @param id: parent id, focused node if None @param includeSelf: set parent node data """ data = data.items() for row in self._iterRowsRecursive( self._idRow[id] if id is not None else self._rs.getRecordNumber(), includeSelf=False ): for field, value in data: self._setFieldValueAt(row, field, value) # interface to tree model def <API key>(self, id): try: row = self._idRow[id] except KeyError: pass else: if row >= 0: return self._rs[row][self._fldParent] def __trigger_getValue(self, id, fieldName): return self._rs[self._idRow[id]][self._rsField(fieldName)] def __trigger_setValue(self, id, fieldName, value): self._rs[self._idRow[id]][self._rsField(fieldName)] = value def __trigger_isLeaf(self, nodeId=None): if nodeId is None: nodeId = self._rs.current[self._fldId] return len(self.__childIds.get(nodeId, ())) == 0 # GFTree class GFTree(GFTreeMixIn, GFTabStop): label = None # Constructor def __init__(self, parent=None): GFTabStop.__init__(self, parent, self.__class__.__name__) GFTreeMixIn.__init__(self) self._triggerFunctions.update({ 'renameNode' : { 'function': self.renameNode }, 'newNode' : { 'function': self.newNode }, 'cutNode' : { 'function': self.cutNode }, 'copyNode' : { 'function': self.copyNode }, 'pasteNode' : { 'function': self.pasteNode }, 'deleteNode' : { 'function': self.deleteNode }, 'getNewNodeParentId' : { 'function': self.<API key> }, '<API key>' : { 'function': self.<API key> }, 'getCuttedNodeId' : { 'function': self.getCuttedNodeId }, 'getCopiedNodeId' : { 'function': self.getCopiedNodeId }, 'expand' : {'function': self.__trigger_expand}, }) self.__columns = None self.__freeze = False # state self.__lastPopupId = None # Initialisation def _phase_1_init_(self): super(GFTree, self)._phase_1_init_() self._block.getDataSource().<API key>({ '<API key>': self.<API key>, # from datasources.GDataSource 'dsResultSetChanged' : self.<API key>, 'dsCursorMoved' : self.__ds_cursor_moved, # from datasources.drivers.Base.ResultSet }) self.__columns = self.findChildrenOfType('GFTreeColumn', includeSelf=False, allowAllChildren=True) def hasLabel(self): return self.label is not None # interface with uiWidget def getColumns(self): return self.__columns # GFTabStop implementation def _is_navigable_(self, mode): # TODO: navigable? hidden? return self._block.navigable and self.navigable # response to events from DataSource def <API key>(self, event): """ - <API key> (parameters: resultSet) whenever the current ResultSet of this datasource changes; this happens when a query is executed or when the master of this datasource moves to another record. - dsResultSetChanged (parameters: resultSet) whenever the current ResultSet has been reloaded from the backend; this happens after each commit if the "requery" option of this datasource is in use. """ # this handler must be called after mixins one try: self.uiWidget.<API key>(self._getIdAt(self._rs.getRecordNumber())) except IndexError: print "! reproduced #228" import sys sys.excepthook(*sys.exc_info()) def __ds_cursor_moved(self, event): """ dsCursorMoved (parameters: none) whenever the cursor in the current ResultSet is moved, i.e. a different record becomes the current record. """ if DEBUG: print 'GFTree.cursor_moved', event if not self.__freeze: if self._rs is not None: self.uiWidget.<API key>(self._getIdAt(self._rs.getRecordNumber())) else: if DEBUG: print "GFTree.cursor_moved and NO RESULTSET YET!" # response to commands from uiTree def _event_menu_popup(self, id): """ call when menu popups and pass node id menu popupped on or None if menu popped up on empty space """ self.__lastPopupId = id def _event_move_node(self, targetId, sourceId): """ set targetId node parent field to sourceId """ self._rs[self._idRow[sourceId]][self._fldParent] = targetId self._revalidate() self._block.goto_record(self._idRow[sourceId]) return True def _event_copy_node(self, targetId, sourceId): #rint '_event_copy_node', targetId, sourceId # this done to avoid tree focus self.__freeze = True self._rs.setRecord(self._idRow[sourceId]) record = self._rs.duplicateRecord(exclude=(self._fldId,)) record[self._fldParent] = targetId self.__freeze = False self._revalidate() try: if self._block.autoCommit: self._form.commit() else: self._block.refresh(False, message=_('Node copied')) except: # server error raise else: self._rs.setRecord(self._idRow[targetId]) return True def <API key>(self): # go to parent record #rs = self._rs #self._block.goto_record(self._idRow[self._rs.current[self._fldParent]]) try: if self._block.autoCommit: self._form.commit() else: # new node created, need to save self._block.refresh(False, message = _("New node created")) except: # server error # here to cleanup if self._block.autoCommit: # rollback self._block.getDataSource().createResultSet(access=self._block.getAccess()) raise def <API key>(self): try: nearestId = self._getIdAt(self._getNearestRow(self._rs.getRecordNumber())) except KeyError: nearestId = None self._rs.current.unmodify() self._revalidate() if nearestId is not None: self._rs.setRecord(self._idRow[nearestId]) def _event_node_checked(self): self.processTrigger('RECORD-CHECKED') def <API key>(self): if self.__lastPopupId is None: return self._rootId else: return self.__lastPopupId def <API key>(self): operations = set() inContext = self.__lastPopupId is not None uiDriverCanModify = self._form.get_uidriver_name() != 'java' # TODO: when access will work ok with trees can set this from block.getAccess() canInsert = True and uiDriverCanModify canUpdate = True and uiDriverCanModify canDelete = True and uiDriverCanModify nodeInClipboard = self.getCuttedNodeId() is not None or self.getCopiedNodeId() is not None if canInsert: operations.add('newNode') if inContext and canUpdate: operations.add('renameNode') if inContext and canUpdate: operations.add('cutNode' ) if inContext and canInsert: operations.add('copyNode') if inContext and (canInsert or canUpdate) and nodeInClipboard: operations.add('pasteNode') if inContext and canDelete: operations.add('deleteNode') operations.add('expand') operations.add('collapse') return operations def getCuttedNodeId(self, force=False): return self.uiWidget.<API key>(force) def getCopiedNodeId(self, force=False): return self.uiWidget.<API key>(force) def __trigger_expand(self, expand=True): self.uiWidget._ui_expand_(self.getIdPath(self.__lastPopupId) if self.__lastPopupId is not None else None, expand) # actions def newNode(self): if self.__lastPopupId is None: id = self._rootId if self._rs.current.isEmpty(): record = self._rs.current else: record = self._rs.appendRecord() else: id = self.__lastPopupId record = self._rs.appendRecord() record[self._fldParent] = id self._revalidate() self._rs.setRecord(self._rs.getRecordCount()-1) # if rs has one just created record, previous setRecord will do nothing so force tree select root node # else _ui_rename_node_ will not work because tree has no selection self.uiWidget.<API key>(self._getIdAt(self._rs.getRecordNumber())) self.uiWidget._ui_rename_node_() def renameNode(self): if self.__lastPopupId not in (None, self._rootId): self.uiWidget._ui_rename_node_() def cutNode(self): if self.__lastPopupId is not None: if self.__lastPopupId != self._rootId: self.uiWidget._ui_cut_node_() else: self._form.show_message(_("Can't cut root"), 'Error') else: self._form.show_message(_("Nothing to cut"), 'Error') def copyNode(self): if self.__lastPopupId is not None: if self.__lastPopupId != self._rootId: self.uiWidget._ui_copy_node_() else: self._form.show_message(_("Can't copy root"), 'Error') else: self._form.show_message(_("Nothing to copy"), 'Error') def pasteNode(self): self.uiWidget._ui_paste_node_() def _getNearestRow(self, currentRow): """ returns parent node row or next sibling row or previous sibling row or KeyError """ parentId = self._rs[currentRow][self._fldParent] try: return self._idRow[parentId] except KeyError: # currentRow is root node, try to go to next root, then to previous root rootRows = [row for row in (self._idRow[id] for id in self.iterChildIds(self._rootId)) if not self._rs[row].isDeleted() or row == currentRow] try: i = rootRows.index(currentRow) except ValueError: # currentRow is not root node, strange, return first root at list i = 0 else: del rootRows[i] if rootRows: return rootRows[min(i, len(rootRows)-1)] else: raise KeyError, 'no other nodes' def deleteNode(self): if self.__lastPopupId == self._rootId: self._form.show_message(u_(u"Can't remove root node"), 'Error') return if not self._rs.current.isEmpty(): rows = list(self._iterRowsRecursive(self._rs.getRecordNumber())) if self._block.autoCommit or self._form.show_message('\n'.join(filter(None, (u_("Are you sure want to delete %s record(s)?") % len(rows), self.deleteMessage))), 'Question'): if self._block.deleteRecords(rows, True, bypassDeletable=True): self.uiWidget._ui_delete_node_() try: self._rs.setRecord(self._getNearestRow(self._rs.getRecordNumber())) except KeyError: pass else: self._form.show_message(u_(u"Nothing to delete"), 'Error')
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>{{ $introduction->story->name }}</title> <!-- Bootstrap --> <link href="/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> <!-- Font Awesome --> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" href="/css/app.css"> @yield('header-include') <!-- 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] </head> <body class="story-view"> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-left"> <p class="navbar-text">{{ Session::get('story-'.$introduction->story->id.'-meter-1-name') }}<br /><span class="lead">${{ Session::get('story-'.$introduction->story->id.'-meter-1-value') }}</span></p> </div> <div class="navbar-right"> <p class="navbar-text text-right">{{ Session::get('story-'.$introduction->story->id.'-meter-2-name') }}<br /><span class="lead">{{ Session::get('story-'.$introduction->story->id.'-meter-2-value') }}</span></p> </div> </div> </nav> @yield('content') <nav class="navbar navbar-default navbar-fixed-bottom"> <div class="container"> <div class="navbar-center"> <p class="navbar-text text-center">Powered by <a href="http://playablemedia.org">Playable Media</a></p> </div> </div> </nav> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="//code.jquery.com/jquery-2.1.4.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="/bootstrap/dist/js/bootstrap.min.js"></script> <!-- Include IFrame-Resizer to support embedding in other contexts --> <script src="https://cdnjs.cloudflare.com/ajax/libs/iframe-resizer/3.5.5/ie8.polyfils.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/iframe-resizer/3.5.5/iframeResizer.contentWindow.min.js"></script> @yield('footer-include') </body> </html>
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ #include <config.h> #include <glib.h> #include <glib/gi18n.h> #include <gthumb.h> #include "gth-catalog.h" #include "gth-organize-task.h" #define GET_WIDGET(name) <API key> (self->priv->builder, (name)) #define KEY_FORMAT ("%Y.%m.%d") enum { NAME_COLUMN = 0, CARDINALITY_COLUMN, <API key>, KEY_COLUMN, ICON_COLUMN }; struct <API key> { GthBrowser *browser; GFile *folder; GthGroupPolicy group_policy; gboolean recursive; gboolean create_singletons; GthCatalog *singletons_catalog; GtkBuilder *builder; GtkWidget *dialog; GtkListStore *results_liststore; GHashTable *catalogs; GdkPixbuf *icon_pixbuf; gboolean organized; GtkWidget *file_list; int n_catalogs; int n_files; GthTest *filter; }; <API key> (GthOrganizeTask, gth_organize_task, GTH_TYPE_TASK, G_ADD_PRIVATE (GthOrganizeTask)) static void <API key> (GObject *object) { GthOrganizeTask *self; self = GTH_ORGANIZE_TASK (object); gtk_widget_destroy (self->priv->dialog); g_object_unref (self->priv->folder); _g_object_unref (self->priv->singletons_catalog); g_object_unref (self->priv->builder); <API key> (self->priv->catalogs); g_object_unref (self->priv->icon_pixbuf); g_object_unref (self->priv->filter); G_OBJECT_CLASS (<API key>)->finalize (object); } static void save_catalog (gpointer key, gpointer value, gpointer user_data) { GthCatalog *catalog = value; gth_catalog_save (catalog); } static void save_catalogs (GthOrganizeTask *self) { GtkTreeIter iter; if (<API key> (GTK_TREE_MODEL (self->priv->results_liststore), &iter)) { do { char *key; char *name; gboolean create; gtk_tree_model_get (GTK_TREE_MODEL (self->priv->results_liststore), &iter, KEY_COLUMN, &key, NAME_COLUMN, &name, <API key>, &create, -1); if (create) { GthCatalog *catalog; char *original_name; catalog = g_hash_table_lookup (self->priv->catalogs, key); /* remove the name if it is equal to the date * to avoid a duplication in the display-name * attribute. */ original_name = <API key> (<API key> (catalog), "%x"); if (g_strcmp0 (original_name, name) != 0) <API key> (catalog, name); else <API key> (catalog, NULL); g_free (original_name); } else g_hash_table_remove (self->priv->catalogs, key); g_free (name); g_free (key); } while (<API key> (GTK_TREE_MODEL (self->priv->results_liststore), &iter)); } <API key> (self->priv->catalogs, save_catalog, NULL); gth_task_completed (GTH_TASK (self), NULL); } static void done_func (GError *error, gpointer user_data) { GthOrganizeTask *self = user_data; char *status_text; if ((error != NULL) && ! g_error_matches (error, G_IO_ERROR, <API key>)) { gth_task_completed (GTH_TASK (self), error); return; } if (! self->priv->create_singletons) { GtkTreeIter iter; int singletons = 0; if (<API key> (GTK_TREE_MODEL (self->priv->results_liststore), &iter)) { do { char *key; int n; gtk_tree_model_get (GTK_TREE_MODEL (self->priv->results_liststore), &iter, KEY_COLUMN, &key, CARDINALITY_COLUMN, &n, -1); if (n == 1) { gtk_list_store_set (self->priv->results_liststore, &iter, <API key>, FALSE, -1); singletons++; if (self->priv->singletons_catalog != NULL) { GthCatalog *catalog; GList *file_list; catalog = g_hash_table_lookup (self->priv->catalogs, key); file_list = <API key> (catalog); <API key> (self->priv->singletons_catalog, file_list->data, -1); if (singletons == 1) g_hash_table_insert (self->priv->catalogs, g_strdup (<API key> (self->priv->singletons_catalog)), g_object_ref (self->priv->singletons_catalog)); } } g_free (key); } while (<API key> (GTK_TREE_MODEL (self->priv->results_liststore), &iter)); } if ((self->priv->singletons_catalog != NULL) && (singletons > 0)) { <API key> (self->priv->results_liststore, &iter); gtk_list_store_set (self->priv->results_liststore, &iter, KEY_COLUMN, <API key> (self->priv->singletons_catalog), NAME_COLUMN, <API key> (self->priv->singletons_catalog), CARDINALITY_COLUMN, <API key> (self->priv->singletons_catalog), <API key>, TRUE, ICON_COLUMN, self->priv->icon_pixbuf, -1); } } self->priv->organized = TRUE; status_text = g_strdup_printf (_("Operation completed. Catalogs: %d. Images: %d."), self->priv->n_catalogs, self->priv->n_files); gtk_label_set_text (GTK_LABEL (GET_WIDGET ("progress_label")), status_text); <API key> (GTK_LABEL (GET_WIDGET ("progress_label")), <API key>); g_free (status_text); <API key> (GET_WIDGET ("cancel_button"), FALSE); <API key> (GTK_DIALOG (self->priv->dialog), GTK_RESPONSE_OK, TRUE); } static GthCatalog * <API key> (GthOrganizeTask *self, const char *catalog_key, GTimeVal *timeval) { GthCatalog *catalog; GthDateTime *date_time; GFile *catalog_file; char *catalog_name; GtkTreeIter iter; GthGroupPolicyData policy_data; catalog = g_hash_table_lookup (self->priv->catalogs, catalog_key); if (catalog != NULL) return catalog; date_time = gth_datetime_new (); <API key> (date_time, timeval); policy_data.task = self; policy_data.date_time = date_time; policy_data.tag = NULL; policy_data.catalog = NULL; policy_data.catalog_file = NULL; gth_hook_invoke ("<API key>", &policy_data); catalog = policy_data.catalog; catalog_file = policy_data.catalog_file; if (catalog == NULL) { _g_object_unref (catalog_file); catalog_file = <API key> (date_time, ".catalog"); catalog = <API key> (catalog_file); } if (catalog == NULL) catalog = gth_catalog_new (); #if 0 date_time = gth_datetime_new (); <API key> (date_time, timeval); catalog_file = NULL; if (<API key> ("search")) { catalog_file = <API key> (date_time, ".search"); catalog = <API key> (catalog_file); } if (catalog == NULL) { _g_object_unref (catalog_file); catalog_file = <API key> (date_time, ".catalog"); catalog = <API key> (catalog_file); } if (catalog == NULL) { if (<API key> ("search")) { GthTest *date_test; GthTest *test_chain; _g_object_unref (catalog_file); catalog_file = <API key> (date_time, ".search"); catalog = (GthCatalog *) gth_search_new (); <API key> (GTH_SEARCH (catalog), self->priv->folder, self->priv->recursive); date_test = <API key> (GTH_TYPE_TEST, (self->priv->group_policy == <API key>) ? "file::mtime" : "Embedded::Photo::DateTimeOriginal"); <API key> (GTH_TEST_SIMPLE (date_test), date_time->date); g_object_set (GTH_TEST_SIMPLE (date_test), "op", GTH_TEST_OP_EQUAL, "negative", FALSE, NULL); test_chain = gth_test_chain_new (GTH_MATCH_TYPE_ALL, date_test, NULL); gth_search_set_test (GTH_SEARCH (catalog), GTH_TEST_CHAIN (test_chain)); g_object_unref (test_chain); g_object_unref (date_test); } else catalog = gth_catalog_new (); } #endif <API key> (catalog, date_time); <API key> (catalog, catalog_file); g_hash_table_insert (self->priv->catalogs, g_strdup (catalog_key), catalog); self->priv->n_catalogs++; catalog_name = <API key> (date_time, "%x"); <API key> (self->priv->results_liststore, &iter); gtk_list_store_set (self->priv->results_liststore, &iter, KEY_COLUMN, catalog_key, NAME_COLUMN, catalog_name, CARDINALITY_COLUMN, 0, <API key>, TRUE, ICON_COLUMN, self->priv->icon_pixbuf, -1); g_free (catalog_name); g_object_unref (catalog_file); gth_datetime_free (date_time); return catalog; } static GthCatalog * add_catalog_for_tag (GthOrganizeTask *self, const char *catalog_key, const char *tag) { GthCatalog *catalog; GFile *catalog_file; GtkTreeIter iter; GthGroupPolicyData policy_data; catalog = g_hash_table_lookup (self->priv->catalogs, catalog_key); if (catalog != NULL) return catalog; policy_data.task = self; policy_data.date_time = NULL; policy_data.tag = tag; policy_data.catalog = NULL; policy_data.catalog_file = NULL; gth_hook_invoke ("<API key>", &policy_data); catalog = policy_data.catalog; catalog_file = policy_data.catalog_file; if (catalog == NULL) { _g_object_unref (catalog_file); catalog_file = <API key> (tag, ".catalog"); catalog = <API key> (catalog_file); } if (catalog == NULL) catalog = gth_catalog_new (); #if 0 catalog_file = NULL; if (<API key> ("search")) { catalog_file = <API key> (tag, ".search"); catalog = <API key> (catalog_file); } if (catalog == NULL) { _g_object_unref (catalog_file); catalog_file = <API key> (tag, ".catalog"); catalog = <API key> (catalog_file); } if (catalog == NULL) { if (<API key> ("search")) { GthTest *tag_test; GthTest *test_chain; _g_object_unref (catalog_file); catalog_file = <API key> (tag, ".search"); catalog = (GthCatalog *) gth_search_new (); <API key> (GTH_SEARCH (catalog), self->priv->folder, self->priv->recursive); tag_test = <API key> (GTH_TYPE_TEST, (self->priv->group_policy == <API key>) ? "comment::category" : "general::tags"); <API key> (GTH_TEST_CATEGORY (tag_test), <API key>, FALSE, tag); test_chain = gth_test_chain_new (GTH_MATCH_TYPE_ALL, tag_test, NULL); gth_search_set_test (GTH_SEARCH (catalog), GTH_TEST_CHAIN (test_chain)); g_object_unref (test_chain); g_object_unref (tag_test); } else catalog = gth_catalog_new (); } #endif <API key> (catalog, catalog_file); g_hash_table_insert (self->priv->catalogs, g_strdup (catalog_key), catalog); self->priv->n_catalogs++; <API key> (self->priv->results_liststore, &iter); gtk_list_store_set (self->priv->results_liststore, &iter, KEY_COLUMN, catalog_key, NAME_COLUMN, tag, CARDINALITY_COLUMN, 0, <API key>, TRUE, ICON_COLUMN, self->priv->icon_pixbuf, -1); g_object_unref (catalog_file); return catalog; } static void add_file_to_catalog (GthOrganizeTask *self, GthCatalog *catalog, const char *catalog_key, GthFileData *file_data) { GtkTreeIter iter; int n = 0; if (! <API key> (catalog, file_data->file, -1)) return; if (<API key> (GTK_TREE_MODEL (self->priv->results_liststore), &iter)) { do { char *k; gtk_tree_model_get (GTK_TREE_MODEL (self->priv->results_liststore), &iter, KEY_COLUMN, &k, CARDINALITY_COLUMN, &n, -1); if (g_strcmp0 (k, catalog_key) == 0) { self->priv->n_files++; n += 1; gtk_list_store_set (self->priv->results_liststore, &iter, CARDINALITY_COLUMN, n, -1); g_free (k); break; } g_free (k); } while (<API key> (GTK_TREE_MODEL (self->priv->results_liststore), &iter)); } } static void for_each_file_func (GFile *file, GFileInfo *info, gpointer user_data) { GthOrganizeTask *self = user_data; GthFileData *file_data; char *catalog_key; GObject *metadata; GTimeVal timeval; GthCatalog *catalog; if (<API key> (info) != G_FILE_TYPE_REGULAR) return; file_data = gth_file_data_new (file, info); if (! gth_test_match (self->priv->filter, file_data)) { g_object_unref (file_data); return; } catalog_key = NULL; switch (self->priv->group_policy) { case <API key>: metadata = <API key> (info, "Embedded::Photo::DateTimeOriginal"); if (metadata != NULL) { if (<API key> (<API key> (GTH_METADATA (metadata)), &timeval)) { catalog_key = <API key> (&timeval, KEY_FORMAT); catalog = <API key> (self, catalog_key, &timeval); add_file_to_catalog (self, catalog, catalog_key, file_data); } } break; case <API key>: timeval = *<API key> (file_data); catalog_key = <API key> (&timeval, KEY_FORMAT); catalog = <API key> (self, catalog_key, &timeval); add_file_to_catalog (self, catalog, catalog_key, file_data); break; case <API key>: case <API key>: if (self->priv->group_policy == <API key>) metadata = <API key> (file_data->info, "comment::categories"); else metadata = <API key> (file_data->info, "general::tags"); if ((metadata != NULL) && GTH_IS_METADATA (metadata)) { GthStringList *categories; GList *list; GList *scan; categories = <API key> (GTH_METADATA (metadata)); list = <API key> (categories); for (scan = list; scan; scan = scan->next) { char *tag = (char *) scan->data; catalog_key = g_strdup (tag); catalog = add_catalog_for_tag (self, catalog_key, tag); add_file_to_catalog (self, catalog, catalog_key, file_data); } } break; } g_free (catalog_key); g_object_unref (file_data); } static DirOp start_dir_func (GFile *directory, GFileInfo *info, GError **error, gpointer user_data) { GthOrganizeTask *self = user_data; char *uri; char *text; uri = <API key> (directory); text = g_strdup_printf ("Searching in %s", uri); gtk_label_set_text (GTK_LABEL (GET_WIDGET ("progress_label")), text); g_free (text); g_free (uri); return DIR_OP_CONTINUE; } static void <API key> (GthTask *base) { GthOrganizeTask *self; const char *attributes = ""; self = GTH_ORGANIZE_TASK (base); self->priv->organized = FALSE; self->priv->n_catalogs = 0; self->priv->n_files = 0; <API key> (self->priv->results_liststore); switch (self->priv->group_policy) { case <API key>: attributes = "standard::name,standard::type,time::modified,time::modified-usec,Embedded::Photo::DateTimeOriginal"; break; case <API key>: attributes = "standard::name,standard::type,time::modified,time::modified-usec"; break; case <API key>: attributes = "standard::name,standard::type,time::modified,time::modified-usec,comment::categories"; break; case <API key>: attributes = "standard::name,standard::type,time::modified,time::modified-usec,general::tags"; break; } <API key> (self->priv->folder, self->priv->recursive, TRUE, attributes, <API key> (GTH_TASK (self)), start_dir_func, for_each_file_func, done_func, self); <API key> (GET_WIDGET ("cancel_button"), TRUE); <API key> (GTK_DIALOG (self->priv->dialog), GTK_RESPONSE_OK, FALSE); <API key> (GTK_WINDOW (self->priv->dialog), GTK_WINDOW (self->priv->browser)); <API key> (GTK_WINDOW (self->priv->dialog), TRUE); gtk_widget_show (self->priv->dialog); gth_task_dialog (base, TRUE, self->priv->dialog); } static void <API key> (GthTask *base) { } static void <API key> (GtkDialog *dialog, int response_id, gpointer user_data) { GthOrganizeTask *self = user_data; if (response_id == <API key>) { if (self->priv->organized) response_id = GTK_RESPONSE_CLOSE; else response_id = GTK_RESPONSE_CANCEL; } if (self->priv->organized && (response_id == GTK_RESPONSE_CANCEL)) response_id = GTK_RESPONSE_CLOSE; switch (response_id) { case GTK_RESPONSE_CANCEL: gth_task_cancel (GTH_TASK (self)); break; case GTK_RESPONSE_CLOSE: gth_task_completed (GTH_TASK (self), NULL); break; case GTK_RESPONSE_OK: save_catalogs (self); break; } } static void <API key> (<API key> *klass) { GObjectClass *object_class; GthTaskClass *task_class; object_class = (GObjectClass*) klass; object_class->finalize = <API key>; task_class = (GthTaskClass*) klass; task_class->exec = <API key>; task_class->cancelled = <API key>; } static void <API key> (GtkCellRendererText *renderer, char *path, char *new_text, gpointer user_data) { GthOrganizeTask *self = user_data; GtkTreePath *tree_path; GtkTreeIter iter; tree_path = <API key> (path); if (! <API key> (GTK_TREE_MODEL (self->priv->results_liststore), &iter, tree_path)) { gtk_tree_path_free (tree_path); return; } gtk_tree_path_free (tree_path); gtk_list_store_set (self->priv->results_liststore, &iter, NAME_COLUMN, new_text, -1); } static void <API key> (<API key> *cell_renderer, char *path, gpointer user_data) { GthOrganizeTask *self = user_data; GtkTreePath *tpath; GtkTreeIter iter; tpath = <API key> (path); if (tpath == NULL) return; if (<API key> (GTK_TREE_MODEL (self->priv->results_liststore), &iter, tpath)) { gboolean create; gtk_tree_model_get (GTK_TREE_MODEL (self->priv->results_liststore), &iter, <API key>, &create, -1); gtk_list_store_set (self->priv->results_liststore, &iter, <API key>, ! create, -1); } gtk_tree_path_free (tpath); } static void <API key> (GList *files, GError *error, gpointer user_data) { GthOrganizeTask *self = user_data; if (error != NULL) return; <API key> (GTH_FILE_LIST (self->priv->file_list), files); } static void <API key> (GtkTreeSelection *treeselection, gpointer user_data) { GthOrganizeTask *self = user_data; GtkTreeIter iter; char *key; GthCatalog *catalog; if (! self->priv->organized) return; if (! <API key> (treeselection, NULL, &iter)) return; gtk_tree_model_get (GTK_TREE_MODEL (self->priv->results_liststore), &iter, KEY_COLUMN, &key, -1); catalog = g_hash_table_lookup (self->priv->catalogs, key); if (catalog != NULL) { GList *file_list; gtk_widget_show (GET_WIDGET ("preview_box")); file_list = <API key> (catalog); <API key> (file_list, GTH_LIST_DEFAULT, <API key>, NULL, <API key>, self); } g_free (key); } static void <API key> (GtkButton *button, gpointer user_data) { GthOrganizeTask *self = user_data; GtkTreeIter iter; if (! <API key> (GTK_TREE_MODEL (self->priv->results_liststore), &iter)) return; do { gtk_list_store_set (self->priv->results_liststore, &iter, <API key>, TRUE, -1); } while (<API key> (GTK_TREE_MODEL (self->priv->results_liststore), &iter)); } static void <API key> (GtkButton *button, gpointer user_data) { GthOrganizeTask *self = user_data; GtkTreeIter iter; if (! <API key> (GTK_TREE_MODEL (self->priv->results_liststore), &iter)) return; do { gtk_list_store_set (self->priv->results_liststore, &iter, <API key>, FALSE, -1); } while (<API key> (GTK_TREE_MODEL (self->priv->results_liststore), &iter)); } static void <API key> (GtkButton *button, gpointer user_data) { GthOrganizeTask *self = user_data; if (! self->priv->organized) gth_task_cancel (GTH_TASK (self)); } static void <API key> (GthOrganizeTask *self) { GIcon *icon; self->priv = <API key> (self); self->priv->builder = <API key> ("organize-files-task.ui", "catalogs"); self->priv->results_liststore = (GtkListStore *) <API key> (self->priv->builder, "results_liststore"); self->priv->catalogs = <API key> (g_str_hash, g_str_equal, g_free, g_object_unref); self->priv->filter = <API key> (); self->priv->dialog = g_object_new (GTK_TYPE_DIALOG, "title", _("Organize Files"), "transient-for", GTK_WINDOW (self->priv->browser), "resizable", TRUE, "use-header-bar", <API key> (), NULL); gtk_container_add (GTK_CONTAINER (<API key> (GTK_DIALOG (self->priv->dialog))), <API key> (self->priv->builder, "dialog_content")); <API key> (GTK_DIALOG (self->priv->dialog), _GTK_LABEL_CANCEL, GTK_RESPONSE_CANCEL, _GTK_LABEL_SAVE, GTK_RESPONSE_OK, NULL); <API key> (GTK_DIALOG (self->priv->dialog), GTK_RESPONSE_OK, <API key>); <API key> (GTK_TREE_SORTABLE (self->priv->results_liststore), KEY_COLUMN, GTK_SORT_ASCENDING); g_object_set (GET_WIDGET ("<API key>"), "editable", TRUE, NULL); icon = g_themed_icon_new ("<API key>"); self->priv->icon_pixbuf = _g_icon_get_pixbuf (icon, <API key> (GET_WIDGET ("<API key>"), GTK_ICON_SIZE_MENU), <API key> (GET_WIDGET ("<API key>"))); g_object_unref (icon); self->priv->file_list = gth_file_list_new (gth_grid_view_new (), <API key>, FALSE); <API key> (GTH_FILE_LIST (self->priv->file_list), NULL); <API key> (GTH_FILE_LIST (self->priv->file_list), "standard::display-name"); <API key> (GTH_FILE_LIST (self->priv->file_list), 128); <API key> (GTH_FILE_LIST (self->priv->file_list), FALSE); gtk_widget_show (self->priv->file_list); <API key> (self->priv->file_list, 350, -1); gtk_box_pack_start (GTK_BOX (GET_WIDGET ("preview_box")), self->priv->file_list, TRUE, TRUE, 0); g_signal_connect (GET_WIDGET ("<API key>"), "edited", G_CALLBACK (<API key>), self); g_signal_connect (GET_WIDGET ("<API key>"), "toggled", G_CALLBACK (<API key>), self); g_signal_connect (self->priv->dialog, "delete-event", G_CALLBACK (gtk_true), NULL); g_signal_connect (self->priv->dialog, "response", G_CALLBACK (<API key>), self); g_signal_connect (<API key> (GTK_TREE_VIEW (GET_WIDGET ("<API key>"))), "changed", G_CALLBACK (<API key>), self); g_signal_connect (GET_WIDGET ("select_all_button"), "clicked", G_CALLBACK (<API key>), self); g_signal_connect (GET_WIDGET ("select_none_button"), "clicked", G_CALLBACK (<API key>), self); g_signal_connect (GET_WIDGET ("cancel_button"), "clicked", G_CALLBACK (<API key>), self); } GthTask * <API key> (GthBrowser *browser, GFile *folder, GthGroupPolicy group_policy) { GthOrganizeTask *self; self = (GthOrganizeTask *) g_object_new (<API key>, NULL); self->priv->browser = browser; self->priv->folder = g_file_dup (folder); self->priv->group_policy = group_policy; return (GthTask*) self; } void <API key> (GthOrganizeTask *self, gboolean recursive) { self->priv->recursive = recursive; } void <API key> (GthOrganizeTask *self, gboolean create) { self->priv->create_singletons = create; } void <API key> (GthOrganizeTask *self, const char *catalog_name) { GFile *file; _g_object_unref (self->priv->singletons_catalog); self->priv->singletons_catalog = NULL; if (catalog_name == NULL) return; self->priv->singletons_catalog = gth_catalog_new (); file = <API key> ("catalog:///", catalog_name, ".catalog"); <API key> (self->priv->singletons_catalog, file); <API key> (self->priv->singletons_catalog, catalog_name); g_object_unref (file); } GFile * <API key> (GthOrganizeTask *self) { return self->priv->folder; } GthGroupPolicy <API key> (GthOrganizeTask *self) { return self->priv->group_policy; } gboolean <API key> (GthOrganizeTask *self) { return self->priv->recursive; }
<?php namespace qtismtest\data\storage\xml\marshalling; use qtismtest\QtiSmTestCase; use qtism\data\storage\xml\marshalling\Marshaller; use qtism\data\ItemSessionControl; use \DOMDocument; use \ReflectionClass; class MarshallerTest extends QtiSmTestCase { public function testCradle() { // Set cradle method accessible $class = new ReflectionClass('qtism\\data\\storage\\xml\\marshalling\\Marshaller'); $method = $class->getMethod('getDOMCradle'); $method->setAccessible(true); $this->assertInstanceOf('\\DOMDocument', $method->invoke(null)); } public function testGetMarshaller() { $component = new ItemSessionControl(); $marshaller = $this-><API key>('2.1.0')->createMarshaller($component); $this->assertInstanceOf('qtism\\data\\storage\\xml\\marshalling\\<API key>', $marshaller); } public function testGetUnmarshaller() { $dom = new DOMDocument('1.0', 'UTF-8'); $dom->loadXML('<itemSessionControl xmlns="http: $marshaller = $this-><API key>('2.1.0')->createMarshaller($dom->documentElement); $this->assertInstanceOf('qtism\\data\\storage\\xml\\marshalling\\<API key>', $marshaller); } public function <API key>() { $dom = new DOMDocument('1.0', 'UTF-8'); $dom->loadXML('<parent>some text <child/> <![CDATA[function() { alert("go!"); }]]></parent>'); $element = $dom->documentElement; $child = Marshaller::<API key>($element); $this->assertInstanceOf('\\DOMElement', $child); $this->assertEquals('child', $child->nodeName); } public function <API key>() { $dom = new DOMDocument('1.0', 'UTF-8'); $dom->loadXML('<parent>some text <![CDATA[function() { alert("stop!"); }]]></parent>'); $element = $dom->documentElement; $this->assertFalse(Marshaller::<API key>($element)); } public function <API key>() { $dom = new DOMDocument('1.0', 'UTF-8'); $dom->loadXML('<parent>some text <child/><anotherChild/> <![CDATA[function() { alert("go!"); }]]></parent>'); $element = $dom->documentElement; $childElements = Marshaller::getChildElements($element); $this->assertInternalType('array', $childElements); $this->assertEquals(2, count($childElements)); $this->assertEquals('child', $childElements[0]->nodeName); $this->assertEquals('anotherChild', $childElements[1]->nodeName); } public function <API key>() { $dom = new DOMDocument('1.0', 'UTF-8'); // There are 3 child elements. 2 at the first level, 1 at the second. // We should find only 2 direct child elements. $dom->loadXML('<parent><child/><child/><parent><child/></parent></parent>'); $element = $dom->documentElement; $this->assertEquals(2, count(Marshaller::<API key>($element, 'child'))); } public function <API key>() { $dom = new DOMDocument('1.0', 'UTF-8'); $dom->loadXML('<parent><child/><child/><grandChild/><uncle/></parent>'); $element = $dom->documentElement; $this->assertEquals(3, count(Marshaller::<API key>($element, array('child', 'grandChild')))); } public function <API key>() { $dom = new DOMDocument('1.0', 'UTF-8'); // There is only 1 child but at the second level. Nothing // should be found. $dom->loadXML('<parent><parent><child/></parent></parent>'); $element = $dom->documentElement; $this->assertEquals(0, count(Marshaller::<API key>($element, 'child'))); } public function testGetXmlBase() { $dom = new DOMDocument('1.0', 'UTF-8'); $dom->loadXML('<foo xml:base="http: $foo = $dom-><API key>('foo')->item(0); $bar = $dom-><API key>('bar')->item(0); $baz = $dom-><API key>('baz')->item(0); $this->assertEquals('http://forge.qtism.com', Marshaller::getXmlBase($foo)); $this->assertFalse(Marshaller::getXmlBase($bar)); $this->assertFalse(Marshaller::getXmlBase($baz)); } /** * @depends testGetXmlBase */ public function testSetXmlBase() { $dom = new DOMDocument('1.0'); $dom->loadXML('<foo><bar>2000</bar><baz>fucked up beyond all recognition</baz></foo>'); $foo = $dom-><API key>('foo')->item(0); $bar = $dom-><API key>('bar')->item(0); $baz = $dom-><API key>('baz')->item(0); $this->assertFalse(Marshaller::getXmlBase($foo)); $this->assertFalse(Marshaller::getXmlBase($bar)); $this->assertFalse(Marshaller::getXmlBase($baz)); Marshaller::setXmlBase($bar, 'http://my-new-base.com'); $this->assertFalse(Marshaller::getXmlBase($foo)); $this->assertEquals('http://my-new-base.com', Marshaller::getXmlBase($bar)); $this->assertFalse(Marshaller::getXmlBase($baz)); } }