code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<div class="footer-social"> <div class="container"> <div class="row"> <div class="col-sm-6"> <h3 style="margin-top:8px; font-weight:300;"></h3> </div> <div class="col-sm-1"> <div class="social"> <div class="social-icon"><a href="#"><i class="icon-twitter"></i></a></div> </div> </div><!--/1--> <div class="col-sm-1"> <div class="social"> <div class="social-icon"><a href="#"><i class="icon-facebook"></i></a></div> </div> </div><!--/1--> <div class="col-sm-1"> <div class="social"> <div class="social-icon"><a href="#"><i class="icon-google-plus"></i></a></div> </div> </div><!--/1--> <div class="col-sm-1"> <div class="social"> <div class="social-icon"><a href="#"><i class="icon-linkedin"></i></a></div> </div> </div><!--/1--> </div> </div> </div> <footer class="footer" role="contentinfo"> <div class="container"> <div id="inner-footer" class="wrap clearfix"> <nav role="navigation"> <div class="row"> <div class="col-md-3 col-sm-3"> <?php bones_footer_links(); ?> </div><!--/3--> <div class="col-md-3 col-sm-3"> <?php bones_footer_links_2(); ?> </div><!--/3--> <div class="col-md-3 col-sm-3"> <?php bones_footer_links_3(); ?> </div><!--/3--> <div class="col-md-3 col-sm-3"> <h4>About Us</h4> <p>Helping our clients grow - with responsible, ethical, and technological leadership. TRUEBADORE is poised to humanize the experience of using technology for meaningful business purposes. TRUEBADORE focuses on aligning aesthetic intelligence and technical prowess so that people will be delighted - not disillusioned - by the new reality that every business is a software business.</p> </div><!--/3--> </div> </nav> </div> <!-- end #inner-footer --> </div> <!-- end .container --> </footer> <!-- end footer --> <div class="footer-copyright"> <div class="container"> <div class="row"> <div class="col-md-10"> <p class="source-org copyright">&copy; <?php echo date('Y'); ?> <?php bloginfo( 'name' ); ?>. All Rights Reserved.</p> </div> <div class="col-md-2"> <a href="#">Back to Top <i class="icon-arrow-up"></i></a> </div> </div> </div> </div> </div> <!-- end .wrapper --> <!-- all js scripts are loaded in library/bones.php --> <?php wp_footer(); ?> </body> </html> <!-- end page. what a ride! -->
truebadore/tba
wp-content/themes/cloudhost/footer.php
PHP
gpl-2.0
3,013
<?php if ( !defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } /** * Manages image sizes settings * * Here image sizes settings are defined and managed. * * @version 1.1.4 * @package ecommerce-product-catalog/functions * @author Norbert Dreszer */ add_action( 'admin_init', 'ic_add_wp_screens_settings' ); function ic_add_wp_screens_settings() { add_settings_section( 'default', __( 'Product Catalog Images', 'ecommerce-product-catalog' ), 'ic_catalog_image_sizes_settings', 'media' ); } function ic_catalog_image_sizes_settings() { $images = ic_get_catalog_image_sizes(); ?> <table class="form-table"> <tbody> <tr> <th scope="row"><?php _e( 'Catalog Single Page Image', 'ecommerce-product-catalog' ) ?></th> <td><fieldset><legend class="screen-reader-text"><span>Large size</span></legend> <label for="product_page_image_w"><?php _e( 'Max Width' ) ?></label> <input name="catalog_image_sizes[product_page_image_w]" type="number" step="1" min="0" id="product_page_image_w" value="<?php echo $images[ 'product_page_image_w' ] ?>" class="small-text"> <label for="product_page_image_h"><?php _e( 'Max Height' ) ?></label> <input name="catalog_image_sizes[product_page_image_h]" type="number" step="1" min="0" id="product_page_image_h" value="<?php echo $images[ 'product_page_image_h' ] ?>" class="small-text"> </fieldset></td> </tr> <tr> <th scope="row"><?php _e( 'Catalog Category Page Image', 'ecommerce-product-catalog' ) ?></th> <td><fieldset><legend class="screen-reader-text"><span>Large size</span></legend> <label for="product_category_page_image_w"><?php _e( 'Max Width' ) ?></label> <input name="catalog_image_sizes[product_category_page_image_w]" type="number" step="1" min="0" id="product_category_page_image_w" value="<?php echo $images[ 'product_category_page_image_w' ] ?>" class="small-text"> <label for="product_category_page_image_h"><?php _e( 'Max Height' ) ?></label> <input name="catalog_image_sizes[product_category_page_image_h]" type="number" step="1" min="0" id="product_category_page_image_h" value="<?php echo $images[ 'product_category_page_image_h' ] ?>" class="small-text"> </fieldset></td> </tr> <tr> <th scope="row"><?php _e( 'Modern Grid Image', 'ecommerce-product-catalog' ) ?></th> <td><fieldset><legend class="screen-reader-text"><span>Large size</span></legend> <label for="modern_grid_image_w"><?php _e( 'Max Width' ) ?></label> <input name="catalog_image_sizes[modern_grid_image_w]" type="number" step="1" min="0" id="product_page_image_w" value="<?php echo $images[ 'modern_grid_image_w' ] ?>" class="small-text"> <label for="modern_grid_image_h"><?php _e( 'Max Height' ) ?></label> <input name="catalog_image_sizes[modern_grid_image_h]" type="number" step="1" min="0" id="product_page_image_h" value="<?php echo $images[ 'modern_grid_image_h' ] ?>" class="small-text"><br> </fieldset></td> </tr> <tr> <th scope="row"><?php _e( 'Classic Grid Image', 'ecommerce-product-catalog' ) ?></th> <td><fieldset><legend class="screen-reader-text"><span><?php _e( 'Classic Grid Image', 'ecommerce-product-catalog' ) ?></span></legend> <label for="classic_grid_image_w"><?php _e( 'Max Width' ) ?></label> <input name="catalog_image_sizes[classic_grid_image_w]" type="number" step="1" min="0" id="product_page_image_w" value="<?php echo $images[ 'classic_grid_image_w' ] ?>" class="small-text"> <label for="classic_grid_image_h"><?php _e( 'Max Height' ) ?></label> <input name="catalog_image_sizes[classic_grid_image_h]" type="number" step="1" min="0" id="product_page_image_h" value="<?php echo $images[ 'classic_grid_image_h' ] ?>" class="small-text"> </fieldset></td> </tr> <tr> <th scope="row"><?php _e( 'Classic List Image', 'ecommerce-product-catalog' ) ?></th> <td><fieldset><legend class="screen-reader-text"><span><?php _e( 'Classic List Image', 'ecommerce-product-catalog' ) ?></span></legend> <label for="classic_list_image_w"><?php _e( 'Max Width' ) ?></label> <input name="catalog_image_sizes[classic_list_image_w]" type="number" step="1" min="0" id="product_page_image_w" value="<?php echo $images[ 'classic_list_image_w' ] ?>" class="small-text"> <label for="classic_list_image_h"><?php _e( 'Max Height' ) ?></label> <input name="catalog_image_sizes[classic_list_image_h]" type="number" step="1" min="0" id="product_page_image_h" value="<?php echo $images[ 'classic_list_image_h' ] ?>" class="small-text"> </fieldset></td> </tr> <?php do_action( 'catalog_image_sizes_settings', $images ) ?> </tbody> </table> <?php } function ic_get_default_catalog_image_sizes() { $image_sizes[ 'product_page_image_w' ] = 600; $image_sizes[ 'product_page_image_h' ] = 600; $image_sizes[ 'product_category_page_image_w' ] = 600; $image_sizes[ 'product_category_page_image_h' ] = 600; $image_sizes[ 'classic_grid_image_w' ] = 600; $image_sizes[ 'classic_grid_image_h' ] = 600; $image_sizes[ 'classic_list_image_w' ] = 280; $image_sizes[ 'classic_list_image_h' ] = 160; $image_sizes[ 'modern_grid_image_w' ] = 600; $image_sizes[ 'modern_grid_image_h' ] = 384; return apply_filters( 'default_catalog_image_sizes', $image_sizes ); } /** * Returns catalog image sizes array * * @return type */ function ic_get_catalog_image_sizes() { $image_sizes = ic_get_global( 'catalog_image_sizes' ); if ( !$image_sizes ) { $default = ic_get_default_catalog_image_sizes(); $image_sizes = wp_parse_args( get_option( 'catalog_image_sizes', $default ), $default ); ic_save_global( 'catalog_image_sizes', $image_sizes ); } return $image_sizes; } add_action( 'product-settings-list', 'ic_register_image_setting' ); /** * Registers catalog image sizes * */ function ic_register_image_setting() { register_setting( 'media', 'catalog_image_sizes' ); } add_action( 'after_setup_theme', 'ic_add_catalog_image_sizes' ); /** * Adds image size for classic grid product listing * */ function ic_add_catalog_image_sizes() { $image_sizes = ic_get_catalog_image_sizes(); add_image_size( 'classic-grid-listing', $image_sizes[ 'classic_grid_image_w' ], $image_sizes[ 'classic_grid_image_h' ] ); add_image_size( 'classic-list-listing', $image_sizes[ 'classic_list_image_w' ], $image_sizes[ 'classic_list_image_h' ] ); add_image_size( 'modern-grid-listing', $image_sizes[ 'modern_grid_image_w' ], $image_sizes[ 'modern_grid_image_h' ], true ); add_image_size( 'product-page-image', $image_sizes[ 'product_page_image_w' ], $image_sizes[ 'product_page_image_h' ] ); add_image_size( 'product-category-page-image', $image_sizes[ 'product_category_page_image_w' ], $image_sizes[ 'product_category_page_image_h' ] ); do_action( 'add_catalog_image_sizes', $image_sizes ); } /** * Generates image size settings table tr * * @param type $label * @param type $name */ function ic_image_sizes_settings_tr( $label, $name ) { $images = ic_get_catalog_image_sizes(); ?> <tr> <th scope="row"><?php echo $label ?></th> <td><fieldset><legend class="screen-reader-text"><span><?php echo $label ?></span></legend> <label for="<?php echo $name . '_w' ?>"><?php _e( 'Max Width' ) ?></label> <input name="catalog_image_sizes[<?php echo $name ?>_w]" type="number" step="1" min="0" id="<?php echo $name ?>_w" value="<?php echo $images[ $name . '_w' ] ?>" class="small-text"> <label for="<?php echo $name . '_h' ?>"><?php _e( 'Max Height' ) ?></label> <input name="catalog_image_sizes[<?php echo $name ?>_h]" type="number" step="1" min="0" id="<?php echo $name ?>_h" value="<?php echo $images[ $name . '_h' ] ?>" class="small-text"> </fieldset></td> </tr><?php }
impleCode/ecommerce-product-catalog
includes/settings/image-sizes.php
PHP
gpl-2.0
7,783
package com.tacohen.killbots.Logic; import android.util.Pair; public class GridDimensions { public static Pair<Integer, Integer> gridDimensions; public static int width; public static int height; public static Pair<Integer, Integer> getGridDimensions() { return gridDimensions; } public static void setGridDimensions(Pair<Integer, Integer> gridDimensions) { GridDimensions.gridDimensions = gridDimensions; } public static int getWidth() { return width; } public static void setWidth(int width) { GridDimensions.width = width; } public static int getHeight() { return height; } public static void setHeight(int height) { GridDimensions.height = height; } }
Tacohen/Killbots
Killbots/src/com/tacohen/killbots/Logic/GridDimensions.java
Java
gpl-2.0
692
<?php /* * Plugin Name: Permalink Redirect * Plugin URI: http://scott.yang.id.au/code/permalink-redirect/ * Description: Permalink Redirect ensures that pages and entries are always accessed via the permalink. Otherwise, a 301 redirect will be issued. * Version: 2.0.5 * Author: Scott Yang * Author URI: http://scott.yang.id.au/ */ class YLSY_PermalinkRedirect { function admin_menu() { add_options_page('Permalink Redirect Manager', 'Permalink Redirect', 5, 'permalink-redirect', array($this, 'admin_page')); } function admin_page() { global $wp_version; // If we are updating, we will flush all the rewrite rules to force the // old structure to be added. if (isset($_GET['updated']) || isset($_GET['settings-updated'])) { $this->regenerate_rules(); } $options = array('feedburner', 'feedburnerbrand', 'hostname', 'oldstruct', 'skip', 'newpath'); $optionvars = array(); foreach ($options as $option) { $$option = get_option("permalink_redirect_$option"); if (!$$option) { $$option = ($option == 'feedburnerbrand') ? 'feeds.feedburner.com' : ''; } if ($wp_version < '2' && !$$option) { add_option("permalink_redirect_$option", $$option); } $optionvars[] = "permalink_redirect_$option"; } $home = parse_url(get_option('home')); ?> <div class="wrap"> <h2>Permalink Redirect Manager</h2> <form action="options.php" method="post"> <fieldset class="options"> <legend>Paths to be skipped</legend> <p>Separate each entry with a new line. Matched with regular expression.</p> <textarea name="permalink_redirect_skip" style="width:98%;" rows="5"><?php echo htmlspecialchars($skip); ?></textarea> <legend style="padding-top:20px">Path pairs to redirect from and to</legend> <p>Separate each entry with a new line. Each line is [from]&lt;spaces&gt;[to].</p> <textarea name="permalink_redirect_newpath" style="width:98%;" rows="5"><?php echo htmlspecialchars($newpath); ?></textarea> <table class="optiontable" style="padding-top:20px"> <tr valign="top"> <th scope="row">Old Permalink Structures:</th> <td><textarea name="permalink_redirect_oldstruct" id="permalink_redirect_oldstruct" style="width:98%" rows="3"><?php echo htmlspecialchars($oldstruct); ?></textarea><br/><small><a href="http://codex.wordpress.org/Using_Permalinks">Available tags</a>. One Permalink Structure per line. Current permalink structure: <a href="#" onclick="document.getElementById('permalink_redirect_oldstruct').value = '<?php echo htmlspecialchars(get_option('permalink_structure')); ?>';return false;"><code><?php echo htmlspecialchars(get_option('permalink_structure')); ?></code></a></small></td> </tr> <tr> <th scope="row">FeedBurner Redirect:</th> <td>http://<input name="permalink_redirect_feedburnerbrand" type="text" id="permalink_redirect_feedburnerbrand" value="<?php print htmlspecialchars($feedburnerbrand); ?>" size="20"/>/<input name="permalink_redirect_feedburner" type="text" id="permalink_redirect_feedburner" value="<?php echo htmlspecialchars($feedburner) ?>" size="20" /></td> </tr> <tr> <th scope="row">Hostname Redirect:</th> <td><input name="permalink_redirect_hostname" type="checkbox" id="permalink_redirect_hostname" value="1"<?php if ($hostname) { ?> checked="checked"<?php } ?>/> Redirect if hostname is not <code><?php echo htmlspecialchars($home['host']); ?></code>.</td> </tr> </table> </fieldset> <p class="submit"> <input type="submit" name="Submit" value="<?php _e('Update Options') ?> &raquo;" /> <input type="hidden" name="action" value="update" /> <input type="hidden" name="page_options" value="<?php echo join(',', $optionvars); ?>"/> <?php if (function_exists('wp_nonce_field')) { wp_nonce_field('update-options'); } ?> </p> </form> </div> <?php } function check_hostname() { if (! get_option('permalink_redirect_hostname')) { return false; } $requested = $_SERVER['HTTP_HOST']; $home = parse_url(get_option('home')); return $requested != $home['host']; } function execute() { global $wp_query; $this->execute2($wp_query); } function execute2($query, $testold=true) { $req_uri = $_SERVER['REQUEST_URI']; if ($query->is_trackback || $query->is_search || $query->is_comments_popup || $query->is_robots || $this->is_skip($req_uri)) { return; } $this->redirect_newpath($req_uri); $this->redirect_feedburner($query); if ($query->is_404) { if ($testold) { $this->redirect_old_permalink($req_uri); } return; } if (($req_uri = @parse_url($_SERVER['REQUEST_URI'])) === false) { return; } $req_path = $req_uri['path']; $new_uri = $this->guess_permalink($query); if (!$new_uri) { return; } $permalink = @parse_url($new_uri); // WP2.1: If a static page has been set as the front-page, we'll get // empty string here. if (!$permalink['path']) { $permalink['path'] = '/'; } if (($req_path != $permalink['path']) || $this->check_hostname()) { wp_redirect($new_uri, 301); } } function guess_permalink($query) { $haspost = count($query->posts) > 0; $has_ut = function_exists('user_trailingslashit'); if (get_query_var('m')) { // Handling special case with '?m=yyyymmddHHMMSS' // Since there is no code for producing the archive links for // is_time, we will give up and not trying any redirection. $m = preg_replace('/[^0-9]/', '', get_query_var('m')); switch (strlen($m)) { case 4: // Yearly $link = get_year_link($m); break; case 6: // Monthly $link = get_month_link(substr($m, 0, 4), substr($m, 4, 2)); break; case 8: // Daily $link = get_day_link(substr($m, 0, 4), substr($m, 4, 2), substr($m, 6, 2)); break; default: return false; } } elseif (($query->is_single || $query->is_page) && $haspost) { $post = $query->posts[0]; $link = get_permalink($post->ID); $page = get_query_var('page'); if ($page && $page > 1) { $link = trailingslashit($link) . "$page"; if ($has_ut) { $link = user_trailingslashit($link, 'paged'); } else { $link .= '/'; } } // WP2.2: In Wordpress 2.2+ is_home() returns false and is_page() // returns true if front page is a static page. if ($query->is_page && ('page' == get_option('show_on_front')) && $post->ID == get_option('page_on_front')) { $link = trailingslashit($link); } } elseif ($query->is_author && $haspost) { global $wp_version; if ($wp_version >= '2') { $author = get_userdata(get_query_var('author')); if ($author === false) return false; if (function_exists('get_author_posts_url')) { $link = get_author_posts_url($author->ID, $author->user_nicename); } else { $link = get_author_link(false, $author->ID, $author->user_nicename); } // XXX: get_author_link seems to always return one with // trailing slash. We have to call user_trailingslashit to // make it right. if ($has_ut) { $link = user_trailingslashit($link); } } else { // XXX: get_author_link() bug in WP 1.5.1.2 // s/author_nicename/user_nicename/ global $cache_userdata; $userid = get_query_var('author'); $link = get_author_link(false, $userid, $cache_userdata[$userid]->user_nicename); } } elseif ($query->is_category && $haspost) { $link = get_category_link(get_query_var('cat')); } elseif ($query->is_tag && $haspost) { $link = get_tag_link(get_query_var('tag_id')); } elseif ($query->is_day && $haspost) { $link = get_day_link(get_query_var('year'), get_query_var('monthnum'), get_query_var('day')); } elseif ($query->is_month && $haspost) { $link = get_month_link(get_query_var('year'), get_query_var('monthnum')); } elseif ($query->is_year && $haspost) { $link = get_year_link(get_query_var('year')); } elseif ($query->is_home) { // WP2.1: Handling "Posts page" option. In WordPress 2.1 is_home() // returns true and is_page() returns false if home page has been // set to a page, and we are getting the permalink of that page // here. if ((get_option('show_on_front') == 'page') && ($pageid = get_option('page_for_posts'))) { $link = trailingslashit(get_permalink($pageid)); } else { $link = trailingslashit(get_option('home')); } } else { return false; } if ($query->is_paged) { $paged = get_query_var('paged'); if ($paged) { $link = trailingslashit($link) . "page/$paged"; if ($has_ut) { $link = user_trailingslashit($link, 'paged'); } else { $link .= '/'; } } } if ($query->is_feed) { $link = trailingslashit($link) . 'feed'; if ($has_ut) { $link = user_trailingslashit($link, 'feed'); } else { $link .= '/'; } } return $link; } function is_feedburner() { return strncmp('FeedBurner/', $_SERVER['HTTP_USER_AGENT'], 11) == 0; } function is_skip($path) { $permalink_redirect_skip = get_option('permalink_redirect_skip'); $permalink_redirect_skip = explode("\n", $permalink_redirect_skip); // Apply 'permalink_redirect_skip' filter so other plugins can // customise the skip behaviour. (Denis de Bernardy @ 2006-04-23) $permalink_redirect_skip = apply_filters('permalink_redirect_skip', $permalink_redirect_skip); foreach ($permalink_redirect_skip as $skip) { $skip = trim($skip); if ($skip && ereg($skip, $path)) return true; } return false; } function redirect_feedburner($query) { // Check whether we need to do redirect for FeedBurner. // NOTE this might not always get executed. For feeds, // WP::send_headers() might send back a 304 before template_redirect // action can be called. global $withcomments; if ($query->is_feed && !$query->is_archive && !$withcomments) { if (($feedburner = get_option('permalink_redirect_feedburner')) && (strncmp('FeedBurner/', $_SERVER['HTTP_USER_AGENT'], 11) != 0)) { $brand = get_option('permalink_redirect_feedburnerbrand'); $brand = $brand ? $brand : 'feeds.feedburner.com'; wp_redirect("http://$brand/$feedburner", 302); } } } // Static page redirect contributed by Sergey Menshikov. function redirect_newpath($path) { if ($newpathlist = get_option('permalink_redirect_newpath')) { $newpathlist = explode("\n", $newpathlist); foreach ($newpathlist as $newpath) { $pair = preg_split('/\s+/', trim($newpath)); if ($pair[0] == $path) { wp_redirect($pair[1], 301); } } } } /** * Called when the main execute function gets a 404 to check against old * permalink structures and perform redirect if an old post can be * matched. */ function redirect_old_permalink($req_uri) { global $wp_query, $wp_rewrite; global $wp_version; $rules = get_option('permalink_redirect_rules'); if (!$rules) { return; } // Backing up the rewrite object for you, imperative programmers! $wp_rewrite_old = $wp_rewrite; // Unsetting the globals. Argh! Evil global variables! foreach ($wp_query->query_vars as $key => $val) { unset($GLOBALS[$key]); } // Going through the rules. foreach ($rules as $rules2) { $wp2 = new WP(); $wp_rewrite = new YLSY_Rewrite(); $wp_rewrite->index = $wp_rewrite_old->index; $wp_rewrite->rules = $rules2; $wp2->parse_request(); if (isset($wp2->query_vars['error']) && ($wp2->query_vars['error'] == 404)) { continue; } $query = new WP_Query(); if ($wp_version >= '2.1') { $posts = $query->query($wp2->query_vars); } else { $wp2->build_query_string(); $posts = $query->query($wp2->query_string); } if (count($posts) > 0) { $wp_rewrite = $wp_rewrite_old; $this->execute2($query, false); return; } } // Restoring global variables. We don't bother to reset the other // variables as we are going to do a 404 anyway. $wp_rewrite = $wp_rewrite_old; } /** * This function is called after someone saved the old permalink * structure. It will create cached version of rewrite rules from the * old structure. */ function regenerate_rules() { global $wp_rewrite; $oldstruct = get_option('permalink_redirect_oldstruct'); if ($oldstruct) { $rules = array(); $oldstruct = explode("\n", $oldstruct); foreach ($oldstruct as $item) { $rules2 = $wp_rewrite->generate_rewrite_rule(trim($item), false, false, false, true); $rules3 = array(); foreach ($rules2 as $match => $query) { $query = preg_replace('/\$(\d+)/', '\$matches[\1]', $query); $rules3[$match] = $query; } $rules[] = $rules3; } update_option('permalink_redirect_rules', $rules); } else { delete_option('permalink_redirect_rules'); } } } /** * I am a dummy class to simulate the WP_Rewite class, but only has one * method implemented. */ class YLSY_Rewrite { function wp_rewrite_rules() { return $this->rules; } } if (!function_exists('wp_redirect')) { function wp_redirect($location, $status=302) { global $is_IIS; $location = apply_filters('wp_redirect', $location, $status); $status = apply_filters('wp_redirect_status', $status, $location); if (!$location) return false; if (function_exists('wp_sanitize_redirect')) { $location = wp_sanitize_redirect($location); } if ($is_IIS) { header("Refresh: 0;url=$location"); } else { status_header($status); header("Location: $location"); } } } $_permalink_redirect = new YLSY_PermalinkRedirect(); add_action('admin_menu', array($_permalink_redirect, 'admin_menu')); add_action('template_redirect', array($_permalink_redirect, 'execute'));
amejias101/wordpress
wp-content/plugins/ylsy_permalink_redirect.php
PHP
gpl-2.0
16,822
//http://codeforces.com/problemset/problem/670/D2 #include <iostream> #include <vector> #include <algorithm> using namespace std; #define printv(data) for(auto& e:data) cout<<e<<","; cout<<endl; #define sortv(data) std::sort(data.begin(),data.end()); #define rsortv(data) std::sort(data.rbegin(),data.rend()); #define fori(start,end) for(size_t i{start};i<end;i++) #define forj(start,end) for(size_t j{start};j<end;j++) #define foralli(data) fori(0,data.size()) constexpr size_t min(size_t a,size_t b){ return a<b?a:b; } constexpr size_t max(size_t a,size_t b){ return a>b?a:b; } using ll = long long; using vll = std::vector<ll>; #define get(var_name) ll var_name{0}; cin >> var_name; #define readv(start,end,vec_name) std::vector<ll> vec_name(end); for(size_t i{start};i<end;i++) cin>>vec_name[i]; constexpr ll BIGLL{ std::numeric_limits<ll>::max() }; constexpr ll LL10{ 10000000000 + 1 }; bool check(vll cookie,vll ingred,ll k,ll num){ foralli(cookie){ ll delta = ingred[i] - cookie[i]*num; if(delta<0){ delta*=-1; if(delta<=k){ k -= delta; }else{ return false; } } } return true; } int main() { ios_base::sync_with_stdio(false); get(n); get(k); readv(0,n,cookie); readv(0,n,ingred); ll l{0},r{LL10}; while(l<=r){ ll m{(l+r)/2}; if(check(cookie,ingred,k,m)){ l = m + 1; }else{ r = m - 1; } } cout<<r<<endl; return 0; }
fjanisze/Problems
D2MagicPowder.cpp
C++
gpl-2.0
1,543
function fileQueueError(file, errorCode, message) { try { var imageName = "error.gif"; var errorName = ""; if (errorCode === SWFUpload.errorCode_QUEUE_LIMIT_EXCEEDED) { errorName = "You have attempted to queue too many files."; } if (errorName !== "") { alert(errorName); return; } switch (errorCode) { case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: imageName = "zerobyte.gif"; break; case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT: imageName = "toobig.gif"; break; case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE: default: alert(message); break; } addImage(images_filepath + imageName); } catch (ex) { this.debug(ex); } } function fileDialogComplete(numFilesSelected, numFilesQueued) { try { if (numFilesQueued > 0) { this.startUpload(); } } catch (ex) { this.debug(ex); } } function uploadProgress(file, bytesLoaded) { try { var percent = Math.ceil((bytesLoaded / file.size) * 100); var progress = new FileProgress(file, this.customSettings.upload_target); progress.setProgress(percent); if (percent === 100) { progress.setStatus("Creating thumbnail..."); progress.toggleCancel(false, this); } else { progress.setStatus("Uploading..."); progress.toggleCancel(true, this); } } catch (ex) { this.debug(ex); } } function uploadSuccess(file, serverData) { try { var progress = new FileProgress(file, this.customSettings.upload_target); if (serverData.substring(0, 7) === "FILEID:") { addImage(serverData.substring(7),serverData.substring(7)); progress.setStatus("Thumbnail Created."); progress.toggleCancel(false); } else { addImage(images_filepath+"error.gif"); progress.setStatus("Error."); progress.toggleCancel(false); alert(serverData); } } catch (ex) { this.debug(ex); } } function uploadComplete(file) { try { /* I want the next upload to continue automatically so I'll call startUpload here */ if (this.getStats().files_queued > 0) { this.startUpload(); } else { var progress = new FileProgress(file, this.customSettings.upload_target); progress.setComplete(); progress.setStatus("All images received."); progress.toggleCancel(false); } } catch (ex) { this.debug(ex); } } function uploadError(file, errorCode, message) { var imageName = "error.gif"; var progress; try { switch (errorCode) { case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED: try { progress = new FileProgress(file, this.customSettings.upload_target); progress.setCancelled(); progress.setStatus("Cancelled"); progress.toggleCancel(false); } catch (ex1) { this.debug(ex1); } break; case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED: try { progress = new FileProgress(file, this.customSettings.upload_target); progress.setCancelled(); progress.setStatus("Stopped"); progress.toggleCancel(true); } catch (ex2) { this.debug(ex2); } case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED: imageName = "uploadlimit.gif"; break; default: alert(message); break; } addImage(images_filepath + imageName); } catch (ex3) { this.debug(ex3); } } function addImage(src,image_id) { var newImg = document.createElement("img"); newImg.setAttribute('id', image_id); newImg.style.margin = "5px"; newImg.style.width='110px'; newImg.style.height='130px'; var newDiv = document.createElement("div"); newDiv.setAttribute('id', 'div_'+image_id); newDiv.setAttribute('class', 'imageBox_label2'); document.getElementById("thumbnails").appendChild(newDiv); document.getElementById('div_'+image_id).appendChild(newImg); if (newImg.filters) { try { newImg.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 0; } catch (e) { // If it is not set initially, the browser will throw an error. This will set it if it is not set yet. newImg.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + 0 + ')'; } } else { newImg.style.opacity = 0; } newImg.onload = function () { fadeIn(newImg, 0); }; newImg.src = src; //create a tag div = document.getElementById('div_'+image_id); var newlink = document.createElement('a'); newlink.setAttribute('id', 'a_photo_'+image_id); newlink.setAttribute('href', 'javascript:void(0);'); newlink.setAttribute('onclick', 'javascript:removePhoto("","'+image_id+'")'); newlink.innerHTML = '<img src="'+img_delete+'" class="img_delete2" alt="" >'; div.appendChild(newlink); } function fadeIn(element, opacity) { var reduceOpacityBy = 5; var rate = 30; // 15 fps if (opacity < 100) { opacity += reduceOpacityBy; if (opacity > 100) { opacity = 100; } if (element.filters) { try { element.filters.item("DXImageTransform.Microsoft.Alpha").opacity = opacity; } catch (e) { // If it is not set initially, the browser will throw an error. This will set it if it is not set yet. element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')'; } } else { element.style.opacity = opacity / 100; } } if (opacity < 100) { setTimeout(function () { fadeIn(element, opacity); }, rate); } } /* ****************************************** * FileProgress Object * Control object for displaying file info * ****************************************** */ function FileProgress(file, targetID) { this.fileProgressID = "divFileProgress"; this.fileProgressWrapper = document.getElementById(this.fileProgressID); if (!this.fileProgressWrapper) { this.fileProgressWrapper = document.createElement("div"); this.fileProgressWrapper.className = "progressWrapper"; this.fileProgressWrapper.id = this.fileProgressID; this.fileProgressElement = document.createElement("div"); this.fileProgressElement.className = "progressContainer"; var progressCancel = document.createElement("a"); progressCancel.className = "progressCancel"; progressCancel.href = "#"; progressCancel.style.visibility = "hidden"; progressCancel.appendChild(document.createTextNode(" ")); var progressText = document.createElement("div"); progressText.className = "progressName"; progressText.appendChild(document.createTextNode(file.name)); var progressBar = document.createElement("div"); progressBar.className = "progressBarInProgress"; var progressStatus = document.createElement("div"); progressStatus.className = "progressBarStatus"; progressStatus.innerHTML = "&nbsp;"; this.fileProgressElement.appendChild(progressCancel); this.fileProgressElement.appendChild(progressText); this.fileProgressElement.appendChild(progressStatus); this.fileProgressElement.appendChild(progressBar); this.fileProgressWrapper.appendChild(this.fileProgressElement); document.getElementById(targetID).appendChild(this.fileProgressWrapper); fadeIn(this.fileProgressWrapper, 0); } else { this.fileProgressElement = this.fileProgressWrapper.firstChild; this.fileProgressElement.childNodes[1].firstChild.nodeValue = file.name; } this.height = this.fileProgressWrapper.offsetHeight; } FileProgress.prototype.setProgress = function (percentage) { this.fileProgressElement.className = "progressContainer green"; this.fileProgressElement.childNodes[3].className = "progressBarInProgress"; this.fileProgressElement.childNodes[3].style.width = percentage + "%"; }; FileProgress.prototype.setComplete = function () { this.fileProgressElement.className = "progressContainer blue"; this.fileProgressElement.childNodes[3].className = "progressBarComplete"; this.fileProgressElement.childNodes[3].style.width = ""; }; FileProgress.prototype.setError = function () { this.fileProgressElement.className = "progressContainer red"; this.fileProgressElement.childNodes[3].className = "progressBarError"; this.fileProgressElement.childNodes[3].style.width = ""; }; FileProgress.prototype.setCancelled = function () { this.fileProgressElement.className = "progressContainer"; this.fileProgressElement.childNodes[3].className = "progressBarError"; this.fileProgressElement.childNodes[3].style.width = ""; }; FileProgress.prototype.setStatus = function (status) { this.fileProgressElement.childNodes[2].innerHTML = status; }; FileProgress.prototype.toggleCancel = function (show, swfuploadInstance) { this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden"; if (swfuploadInstance) { var fileID = this.fileProgressID; this.fileProgressElement.childNodes[0].onclick = function () { swfuploadInstance.cancelUpload(fileID); return false; }; } };
vapvarun/MicrocerptBIZ
wp-content/plugins/PlusOnett/monetize/add_post/image_uploader/swfupload/handlers.js
JavaScript
gpl-2.0
8,928
/** * Copyright (C) 2012-2016 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package org.n52.server.da.oxf; import org.n52.oxf.sos.adapter.ISOSRequestBuilder; import org.n52.oxf.sos.adapter.SOSRequestBuilderFactory; import org.n52.oxf.sos.util.SosUtil; public class SosRequestBuilderFactory { public static ISOSRequestBuilder createRequestBuilder(String serviceVersion) { if (SosUtil.isVersion100(serviceVersion)) { return new SOSRequestBuilder_100_OXFExtension(); } else if (SosUtil.isVersion200(serviceVersion)) { return new SOSRequestBuilder_200_OXFExtension(); } else { return SOSRequestBuilderFactory.generateRequestBuilder(serviceVersion); } } }
ridoo/SensorWebClient
sensorwebclient-api/src/main/java/org/n52/server/da/oxf/SosRequestBuilderFactory.java
Java
gpl-2.0
1,956
<?php /* define package */ define('PKG_NAME', 'VoteForms'); define('PKG_NAME_LOWER', strtolower(PKG_NAME)); define('PKG_VERSION', '2.0.5'); define('PKG_RELEASE', 'beta'); define('PKG_AUTO_INSTALL', true); /* define paths */ if (isset($_SERVER['MODX_BASE_PATH'])) { define('MODX_BASE_PATH', $_SERVER['MODX_BASE_PATH']); } elseif (file_exists(dirname(dirname(dirname(__FILE__))) . '/core')) { define('MODX_BASE_PATH', dirname(dirname(dirname(__FILE__))) . '/'); } else { define('MODX_BASE_PATH', dirname(dirname(dirname(dirname(__FILE__)))) . '/'); } define('MODX_CORE_PATH', MODX_BASE_PATH . 'core/'); define('MODX_MANAGER_PATH', MODX_BASE_PATH . 'manager/'); define('MODX_CONNECTORS_PATH', MODX_BASE_PATH . 'connectors/'); define('MODX_ASSETS_PATH', MODX_BASE_PATH . 'assets/'); /* define urls */ define('MODX_BASE_URL', '/'); define('MODX_CORE_URL', MODX_BASE_URL . 'core/'); define('MODX_MANAGER_URL', MODX_BASE_URL . 'manager/'); define('MODX_CONNECTORS_URL', MODX_BASE_URL . 'connectors/'); define('MODX_ASSETS_URL', MODX_BASE_URL . 'assets/'); /* define build options */ define('BUILD_MENU_UPDATE', true); define('BUILD_ACTION_UPDATE', true); define('BUILD_SETTING_UPDATE', true); define('BUILD_CHUNK_UPDATE', true); define('BUILD_SNIPPET_UPDATE', true); define('BUILD_PLUGIN_UPDATE', true); //define('BUILD_EVENT_UPDATE', true); //define('BUILD_POLICY_UPDATE', true); //define('BUILD_POLICY_TEMPLATE_UPDATE', true); //define('BUILD_PERMISSION_UPDATE', true); if (!empty($_GET['development'])) { define('PKG_NAMESPACE_PATH', '{base_path}' . PKG_NAME . '/core/components/' . PKG_NAME_LOWER . '/'); define('PKG_CORE_PATH', MODX_BASE_PATH . PKG_NAME . '/core/components/' . PKG_NAME_LOWER . '/'); define('PKG_STATIC_PATH', PKG_NAME . '/core/components/' . PKG_NAME_LOWER); define('PKG_ASSETS_URL', '/' . PKG_NAME .'/assets/components/' . PKG_NAME_LOWER . '/'); define('BUILD_CHUNK_STATIC', true); define('BUILD_SNIPPET_STATIC', true); define('BUILD_PLUGIN_STATIC', true); } else { define('PKG_NAMESPACE_PATH', '{core_path}components/' . PKG_NAME_LOWER . '/'); define('PKG_CORE_PATH', '{core_path}components/' . PKG_NAME_LOWER . '/'); define('PKG_STATIC_PATH', 'core/components/' . PKG_NAME_LOWER); define('PKG_ASSETS_URL', '{assets_url}components/' . PKG_NAME_LOWER . '/'); define('BUILD_CHUNK_STATIC', false); define('BUILD_SNIPPET_STATIC', false); define('BUILD_PLUGIN_STATIC', false); } $BUILD_RESOLVERS = array( 'tables', 'chunks', 'setup', );
me6iaton/VoteForms
_build/build.config.php
PHP
gpl-2.0
2,496
// // ID Engine // ID_IN.c - Input Manager // v1.0d1 // By Jason Blochowiak // // // This module handles dealing with the various input devices // // Depends on: Memory Mgr (for demo recording), Sound Mgr (for timing stuff), // User Mgr (for command line parms) // // Globals: // LastScan - The keyboard scan code of the last key pressed // LastASCII - The ASCII value of the last key pressed // DEBUG - there are more globals // #include "wl_def.h" void IN_GetJoyDelta(int *dx,int *dy) { (void)dx; (void)dy; } /* ============================================================================= GLOBAL VARIABLES ============================================================================= */ #ifdef USE_SDL // // configuration variables // boolean MousePresent; boolean forcegrabmouse; // Global variables volatile boolean Keyboard[SDLK_LAST]; volatile boolean Paused; volatile char LastASCII; volatile ScanCode LastScan; //KeyboardDef KbdDefs = {0x1d,0x38,0x47,0x48,0x49,0x4b,0x4d,0x4f,0x50,0x51}; static KeyboardDef KbdDefs = { sc_Control, // button0 sc_Alt, // button1 sc_Home, // upleft sc_UpArrow, // up sc_PgUp, // upright sc_LeftArrow, // left sc_RightArrow, // right sc_End, // downleft sc_DownArrow, // down sc_PgDn // downright }; static SDL_Joystick *Joystick; int JoyNumButtons; static int JoyNumHats; static bool GrabInput = false; /* ============================================================================= LOCAL VARIABLES ============================================================================= */ byte ASCIINames[] = // Unshifted ASCII for scan codes // TODO: keypad { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,8 ,9 ,0 ,0 ,0 ,13 ,0 ,0 , // 0 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,27 ,0 ,0 ,0 , // 1 ' ',0 ,0 ,0 ,0 ,0 ,0 ,39 ,0 ,0 ,'*','+',',','-','.','/', // 2 '0','1','2','3','4','5','6','7','8','9',0 ,';',0 ,'=',0 ,0 , // 3 '`','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o', // 4 'p','q','r','s','t','u','v','w','x','y','z','[',92 ,']',0 ,0 , // 5 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , // 6 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 // 7 }; byte ShiftNames[] = // Shifted ASCII for scan codes { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,8 ,9 ,0 ,0 ,0 ,13 ,0 ,0 , // 0 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,27 ,0 ,0 ,0 , // 1 ' ',0 ,0 ,0 ,0 ,0 ,0 ,34 ,0 ,0 ,'*','+','<','_','>','?', // 2 ')','!','@','#','$','%','^','&','*','(',0 ,':',0 ,'+',0 ,0 , // 3 '~','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O', // 4 'P','Q','R','S','T','U','V','W','X','Y','Z','{','|','}',0 ,0 , // 5 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , // 6 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 // 7 }; byte SpecialNames[] = // ASCII for 0xe0 prefixed codes { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , // 0 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,13 ,0 ,0 ,0 , // 1 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , // 2 0 ,0 ,0 ,0 ,0 ,'/',0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , // 3 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , // 4 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , // 5 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , // 6 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 // 7 }; static boolean IN_Started; static Direction DirTable[] = // Quick lookup for total direction { dir_NorthWest, dir_North, dir_NorthEast, dir_West, dir_None, dir_East, dir_SouthWest, dir_South, dir_SouthEast }; /////////////////////////////////////////////////////////////////////////// // // INL_GetMouseButtons() - Gets the status of the mouse buttons from the // mouse driver // /////////////////////////////////////////////////////////////////////////// static int INL_GetMouseButtons(void) { int buttons = SDL_GetMouseState(NULL, NULL); int middlePressed = buttons & SDL_BUTTON(SDL_BUTTON_MIDDLE); int rightPressed = buttons & SDL_BUTTON(SDL_BUTTON_RIGHT); buttons &= ~(SDL_BUTTON(SDL_BUTTON_MIDDLE) | SDL_BUTTON(SDL_BUTTON_RIGHT)); if(middlePressed) buttons |= 1 << 2; if(rightPressed) buttons |= 1 << 1; return buttons; } /////////////////////////////////////////////////////////////////////////// // // IN_GetJoyDelta() - Returns the relative movement of the specified // joystick (from +/-127) // /////////////////////////////////////////////////////////////////////////// void IN_GetJoyDelta(int *dx,int *dy) { if(!Joystick) { *dx = *dy = 0; return; } SDL_JoystickUpdate(); #ifdef _arch_dreamcast int x = 0; int y = 0; #else int x = SDL_JoystickGetAxis(Joystick, 0) >> 8; int y = SDL_JoystickGetAxis(Joystick, 1) >> 8; #endif if(param_joystickhat != -1) { uint8_t hatState = SDL_JoystickGetHat(Joystick, param_joystickhat); if(hatState & SDL_HAT_RIGHT) x += 127; else if(hatState & SDL_HAT_LEFT) x -= 127; if(hatState & SDL_HAT_DOWN) y += 127; else if(hatState & SDL_HAT_UP) y -= 127; if(x < -128) x = -128; else if(x > 127) x = 127; if(y < -128) y = -128; else if(y > 127) y = 127; } *dx = x; *dy = y; } /////////////////////////////////////////////////////////////////////////// // // IN_GetJoyFineDelta() - Returns the relative movement of the specified // joystick without dividing the results by 256 (from +/-127) // /////////////////////////////////////////////////////////////////////////// void IN_GetJoyFineDelta(int *dx, int *dy) { if(!Joystick) { *dx = 0; *dy = 0; return; } SDL_JoystickUpdate(); int x = SDL_JoystickGetAxis(Joystick, 0); int y = SDL_JoystickGetAxis(Joystick, 1); if(x < -128) x = -128; else if(x > 127) x = 127; if(y < -128) y = -128; else if(y > 127) y = 127; *dx = x; *dy = y; } /* =================== = = IN_JoyButtons = =================== */ int IN_JoyButtons() { if(!Joystick) return 0; SDL_JoystickUpdate(); int res = 0; for(int i = 0; i < JoyNumButtons && i < 32; i++) res |= SDL_JoystickGetButton(Joystick, i) << i; return res; } boolean IN_JoyPresent() { return Joystick != NULL; } static void processEvent(SDL_Event *event) { switch (event->type) { // exit if the window is closed case SDL_QUIT: Quit(NULL); // check for keypresses case SDL_KEYDOWN: { if(event->key.keysym.sym==SDLK_SCROLLOCK || event->key.keysym.sym==SDLK_F12) { GrabInput = !GrabInput; SDL_WM_GrabInput(GrabInput ? SDL_GRAB_ON : SDL_GRAB_OFF); return; } LastScan = event->key.keysym.sym; SDLMod mod = SDL_GetModState(); if(Keyboard[sc_Alt]) { if(LastScan==SDLK_F4) Quit(NULL); } if(LastScan == SDLK_KP_ENTER) LastScan = SDLK_RETURN; else if(LastScan == SDLK_RSHIFT) LastScan = SDLK_LSHIFT; else if(LastScan == SDLK_RALT) LastScan = SDLK_LALT; else if(LastScan == SDLK_RCTRL) LastScan = SDLK_LCTRL; else { if((mod & KMOD_NUM) == 0) { switch(LastScan) { case SDLK_KP2: LastScan = SDLK_DOWN; break; case SDLK_KP4: LastScan = SDLK_LEFT; break; case SDLK_KP6: LastScan = SDLK_RIGHT; break; case SDLK_KP8: LastScan = SDLK_UP; break; } } } int sym = LastScan; if(sym >= 'a' && sym <= 'z') sym -= 32; // convert to uppercase if(mod & (KMOD_SHIFT | KMOD_CAPS)) { if(sym < lengthof(ShiftNames) && ShiftNames[sym]) LastASCII = ShiftNames[sym]; } else { if(sym < lengthof(ASCIINames) && ASCIINames[sym]) LastASCII = ASCIINames[sym]; } if(LastScan<SDLK_LAST) Keyboard[LastScan] = 1; if(LastScan == SDLK_PAUSE) Paused = true; break; } case SDL_KEYUP: { int key = event->key.keysym.sym; if(key == SDLK_KP_ENTER) key = SDLK_RETURN; else if(key == SDLK_RSHIFT) key = SDLK_LSHIFT; else if(key == SDLK_RALT) key = SDLK_LALT; else if(key == SDLK_RCTRL) key = SDLK_LCTRL; else { if((SDL_GetModState() & KMOD_NUM) == 0) { switch(key) { case SDLK_KP2: key = SDLK_DOWN; break; case SDLK_KP4: key = SDLK_LEFT; break; case SDLK_KP6: key = SDLK_RIGHT; break; case SDLK_KP8: key = SDLK_UP; break; } } } if(key<SDLK_LAST) Keyboard[key] = 0; break; } #if defined(GP2X) case SDL_JOYBUTTONDOWN: GP2X_ButtonDown(event->jbutton.button); break; case SDL_JOYBUTTONUP: GP2X_ButtonUp(event->jbutton.button); break; #endif } } void IN_WaitAndProcessEvents() { SDL_Event event; if(!SDL_WaitEvent(&event)) return; do { processEvent(&event); } while(SDL_PollEvent(&event)); } void IN_ProcessEvents() { SDL_Event event; while (SDL_PollEvent(&event)) { processEvent(&event); } } /////////////////////////////////////////////////////////////////////////// // // IN_Startup() - Starts up the Input Mgr // /////////////////////////////////////////////////////////////////////////// void IN_Startup(void) { if (IN_Started) return; IN_ClearKeysDown(); if(param_joystickindex >= 0 && param_joystickindex < SDL_NumJoysticks()) { Joystick = SDL_JoystickOpen(param_joystickindex); if(Joystick) { JoyNumButtons = SDL_JoystickNumButtons(Joystick); if(JoyNumButtons > 32) JoyNumButtons = 32; // only up to 32 buttons are supported JoyNumHats = SDL_JoystickNumHats(Joystick); if(param_joystickhat < -1 || param_joystickhat >= JoyNumHats) Quit("The joystickhat param must be between 0 and %i!", JoyNumHats - 1); } } SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE); if(fullscreen || forcegrabmouse) { GrabInput = true; SDL_WM_GrabInput(SDL_GRAB_ON); } // I didn't find a way to ask libSDL whether a mouse is present, yet... #if defined(GP2X) MousePresent = false; #elif defined(_arch_dreamcast) MousePresent = DC_MousePresent(); #else MousePresent = true; #endif IN_Started = true; } /////////////////////////////////////////////////////////////////////////// // // IN_Shutdown() - Shuts down the Input Mgr // /////////////////////////////////////////////////////////////////////////// void IN_Shutdown(void) { if (!IN_Started) return; if(Joystick) SDL_JoystickClose(Joystick); IN_Started = false; } /////////////////////////////////////////////////////////////////////////// // // IN_ClearKeysDown() - Clears the keyboard array // /////////////////////////////////////////////////////////////////////////// void IN_ClearKeysDown(void) { LastScan = sc_None; LastASCII = key_None; memset ((void *) Keyboard,0,sizeof(Keyboard)); } /////////////////////////////////////////////////////////////////////////// // // IN_ReadControl() - Reads the device associated with the specified // player and fills in the control info struct // /////////////////////////////////////////////////////////////////////////// void IN_ReadControl(int player,ControlInfo *info) { word buttons; int dx,dy; Motion mx,my; dx = dy = 0; mx = my = motion_None; buttons = 0; IN_ProcessEvents(); if (Keyboard[KbdDefs.upleft]) mx = motion_Left,my = motion_Up; else if (Keyboard[KbdDefs.upright]) mx = motion_Right,my = motion_Up; else if (Keyboard[KbdDefs.downleft]) mx = motion_Left,my = motion_Down; else if (Keyboard[KbdDefs.downright]) mx = motion_Right,my = motion_Down; if (Keyboard[KbdDefs.up]) my = motion_Up; else if (Keyboard[KbdDefs.down]) my = motion_Down; if (Keyboard[KbdDefs.left]) mx = motion_Left; else if (Keyboard[KbdDefs.right]) mx = motion_Right; if (Keyboard[KbdDefs.button0]) buttons += 1 << 0; if (Keyboard[KbdDefs.button1]) buttons += 1 << 1; dx = mx * 127; dy = my * 127; info->x = dx; info->xaxis = mx; info->y = dy; info->yaxis = my; info->button0 = (buttons & (1 << 0)) != 0; info->button1 = (buttons & (1 << 1)) != 0; info->button2 = (buttons & (1 << 2)) != 0; info->button3 = (buttons & (1 << 3)) != 0; info->dir = DirTable[((my + 1) * 3) + (mx + 1)]; } /////////////////////////////////////////////////////////////////////////// // // IN_WaitForKey() - Waits for a scan code, then clears LastScan and // returns the scan code // /////////////////////////////////////////////////////////////////////////// ScanCode IN_WaitForKey(void) { ScanCode result; while ((result = LastScan)==0) IN_WaitAndProcessEvents(); LastScan = 0; return(result); } /////////////////////////////////////////////////////////////////////////// // // IN_WaitForASCII() - Waits for an ASCII char, then clears LastASCII and // returns the ASCII value // /////////////////////////////////////////////////////////////////////////// char IN_WaitForASCII(void) { char result; while ((result = LastASCII)==0) IN_WaitAndProcessEvents(); LastASCII = '\0'; return(result); } /////////////////////////////////////////////////////////////////////////// // // IN_Ack() - waits for a button or key press. If a button is down, upon // calling, it must be released for it to be recognized // /////////////////////////////////////////////////////////////////////////// boolean btnstate[NUMBUTTONS]; void IN_StartAck(void) { IN_ProcessEvents(); // // get initial state of everything // IN_ClearKeysDown(); memset(btnstate, 0, sizeof(btnstate)); int buttons = IN_JoyButtons() << 4; if(MousePresent) buttons |= IN_MouseButtons(); for(int i = 0; i < NUMBUTTONS; i++, buttons >>= 1) if(buttons & 1) btnstate[i] = true; } boolean IN_CheckAck (void) { IN_ProcessEvents(); // // see if something has been pressed // if(LastScan) return true; int buttons = IN_JoyButtons() << 4; if(MousePresent) buttons |= IN_MouseButtons(); for(int i = 0; i < NUMBUTTONS; i++, buttons >>= 1) { if(buttons & 1) { if(!btnstate[i]) { // Wait until button has been released do { IN_WaitAndProcessEvents(); buttons = IN_JoyButtons() << 4; if(MousePresent) buttons |= IN_MouseButtons(); } while(buttons & (1 << i)); return true; } } else btnstate[i] = false; } return false; } void IN_Ack (void) { IN_StartAck (); do { IN_WaitAndProcessEvents(); } while(!IN_CheckAck ()); } /////////////////////////////////////////////////////////////////////////// // // IN_UserInput() - Waits for the specified delay time (in ticks) or the // user pressing a key or a mouse button. If the clear flag is set, it // then either clears the key or waits for the user to let the mouse // button up. // /////////////////////////////////////////////////////////////////////////// boolean IN_UserInput(longword delay) { longword lasttime; lasttime = GetTimeCount(); IN_StartAck (); do { IN_ProcessEvents(); if (IN_CheckAck()) return true; DelayMS(5); } while (GetTimeCount() - lasttime < delay); return(false); } //=========================================================================== /* =================== = = IN_MouseButtons = =================== */ int IN_MouseButtons (void) { if (MousePresent) return INL_GetMouseButtons(); else return 0; } bool IN_IsInputGrabbed() { return GrabInput; } void IN_CenterMouse() { SDL_WarpMouse(screenWidth / 2, screenHeight / 2); } #endif
WarlockD/crispy-doom
stm32/wolf3d/id_in.cpp
C++
gpl-2.0
17,126
<div class="mcl-login-form-login"> <h2><?php echo ($instance_id == "my_columbia_llm") ? "My Columbia LL.M." : "My Columbia Law and Admitted Student" ?></h2> <h3>Security Question Update</h3> <div <?php echo (isset($_SESSION['messages']['status'][0])) ? "class='status-msg'" : "" ?> > <?php echo (isset($_SESSION['messages']['status'][0])) ? $_SESSION['messages']['status'][0] : "" ?> </div> <div <?php echo (isset($_SESSION['messages']['error'][0])) ? "class='error-msg'" : "" ?> > <?php echo (isset($_SESSION['messages']['error'][0])) ? $_SESSION['messages']['error'][0] : "" ?> </div> <?php echo drupal_render($form); ?> <p class="back-to-login"> <a id="back-to-login-link" href="<?php echo base_path() ?>admissions/jd/my-columbia-law">Back to Login Page</a> </p> </div> <style type="text/css"> body div.messages {display: none;} .menu-mlid-4476 a {color:#333333;} div.mcl-login-form-login label { font-weight: bold; font-size: 13px; color: #333333; } div.mcl-login-form-login div#edit-actions { margin-bottom: 0 !important; margin-top: 15px !important; } div.mcl-login-form-login label span.form-required { display: none; } div.error-msg { background-color: #FEF5F1; color: #8C2E0B; border: 1px solid #ED541D; background-image: url("/misc/message-24-error.png"); background-position: 8px 8px; background-repeat: no-repeat; margin: 6px 0; padding: 10px 10px 10px 50px; font-size: 13px; } div.status-msg { background-color: #F8FFF0; color: #234600; border: 1px solid #BBEE77; background-image: url("/misc/message-24-ok.png"); background-position: 8px 8px; background-repeat: no-repeat; margin: 6px 0; padding: 10px 10px 10px 50px; font-size: 13px; } div.mcl-login-form-login input#edit-submit { border-radius: 15px; -moz-border-radius: 15px; -webkit-border-radius: 15px; background-color: #333333; border: 2px solid #999999; color: #FFFFFF; font: 15px Verdana, Arial, sans-serif; padding: 3px 15px 5px; margin-bottom: 15px; margin-top: 10px; } div.mcl-login-form-login input#edit-submit:active { background-color: #186E9E; color: #FFFFFF; } div.mcl-login-form-login select#edit-security-question-select { width: 345px; font: 12px/10px Verdana,Arial,Helvetica,sans-serif; margin: 10px 0 15px; } div.mcl-login-form-login select#edit-security-question-select, div.mcl-login-form-login input#edit-security-question-other, div.mcl-login-form-login input#edit-security-answer { background-color: #FFFFFF; border: 2px solid #999999; color: #666666; display: block; height: 25px; padding: 1px 10px 3px; } div.mcl-login-form-login input#edit-security-question-other, div.mcl-login-form-login input#edit-security-answer { border-radius:15px; -moz-border-radius:15px; -webkit-border-radius:15px; font: 21px/18px Verdana,Arial,Helvetica,sans-serif; width: 321px; margin: 10px 0; } div.mcl-login-form-login select#edit-security-question-select:focus, div.mcl-login-form-login input#edit-security-question-other:focus, div.mcl-login-form-login input#edit-security-answer { border: #186E9E 2px solid; } p#mcl-security-answer { font-size: 13px; margin-top: 10px; } body div#cls-mcl-account-errors { background-image: none; margin: 0 0 20px; } body div#cls-mcl-account-errors label { width: auto; float: none; color: #cc0000; } body div#cls-mcl-account-errors li { margin: 0 0 5px 15px; color: #cc0000; } div#cls-mcl-account-errors:after { clear: both; content: " "; display: block; font-size: 0; height: 0; line-height: 0; visibility: hidden; width: 0; } </style>
nexttee/culaw
sites/default/modules/cls_mcl/templates/security_question_update.tpl.php
PHP
gpl-2.0
3,687
$Rev: 916 $
boudewijnrempt/HyvesDesktop
3rdparty/socorro/webapp-php/application/views/common/version.php
PHP
gpl-2.0
13
package utility; public class IdConst extends Ident { //Valeur de la constante private int valeur; //Initialisation d'une IdConst (nom, type et valeur) public IdConst(String _name, int _type, int _valeur) { super(_name, _type); //constructeur de Ident this.valeur = _valeur; } public int getValeur() {return this.valeur;} public void setValeur(int _v) {this.valeur = _v;} //Verificateur de type public boolean isConst() {return true;} }
william-insa/Projet_compilateur
Compilateur/src/utility/IdConst.java
Java
gpl-2.0
455
/********************************************************************** Freeciv - Copyright (C) 1996 - A Kjeldberg, L Gregersen, P Unold This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ***********************************************************************/ #ifndef WC_COMMON_WORKLIST_H #define WC_COMMON_WORKLIST_H #include "shared.hh" /* MAX_LEN_NAME */ #define MAX_LEN_WORKLIST 16 #define MAX_NUM_WORKLISTS 16 /* worklist element flags */ enum worklist_elem_flag { WEF_END, /* element is past end of list */ WEF_UNIT, /* element specifies a unit to be built */ WEF_IMPR, /* element specifies an improvement to be built */ WEF_LAST /* leave this last */ }; /* a worklist */ struct worklist { bool is_valid; char name[MAX_LEN_NAME]; enum worklist_elem_flag wlefs[MAX_LEN_WORKLIST]; int wlids[MAX_LEN_WORKLIST]; }; void init_worklist(struct worklist *pwl); int worklist_length(const struct worklist *pwl); bool worklist_is_empty(const struct worklist *pwl); bool worklist_peek(const struct worklist *pwl, int *id, bool *is_unit); bool worklist_peek_ith(const struct worklist *pwl, int *id, bool *is_unit, int idx); void worklist_advance(struct worklist *pwl); void copy_worklist(struct worklist *dst, const struct worklist *src); void worklist_remove(struct worklist *pwl, int idx); bool worklist_append(struct worklist *pwl, int id, bool is_unit); bool worklist_insert(struct worklist *pwl, int id, bool is_unit, int idx); bool are_worklists_equal(const struct worklist *wlist1, const struct worklist *wlist2); #endif /* WC_COMMON_WORKLIST_H */
seggil/warciv
common/worklist.hh
C++
gpl-2.0
2,086
<?php /* ----------------------------------------------------------------------------------------- $Id: xtc_get_uprid.inc.php 899 2005-04-29 02:40:57Z hhgag $ XT-Commerce - community made shopping http://www.xt-commerce.com Copyright (c) 2003 XT-Commerce ----------------------------------------------------------------------------------------- based on: (c) 2000-2001 The Exchange Project (earlier name of osCommerce) (c) 2002-2003 osCommerce(general.php,v 1.225 2003/05/29); www.oscommerce.com (c) 2003 nextcommerce (xtc_get_uprid.inc.php,v 1.3 2003/08/13); www.nextcommerce.org Released under the GNU General Public License ---------------------------------------------------------------------------------------*/ // Return a product ID with attributes function xtc_get_uprid($prid, $params) { global $scModules; if (is_numeric($prid)) { $uprid = $prid; if (is_array($params) && (sizeof($params) > 0)) { $attributes_check = true; $attributes_ids = ''; reset($params); while (list($option, $value) = each($params)) { //new module support list($option, $value) = (class_exists('shoppingCartModules') ? $scModules->get_uprid(array($option, $value)) : array($option, $value)); if (is_numeric($option) && is_numeric($value)) { $attributes_ids .= '{' . (int)$option . '}' . (int)$value; } else { $attributes_check = false; break; } } if ($attributes_check == true) { $uprid .= $attributes_ids; } } } else { $uprid = xtc_get_prid($prid); if (is_numeric($uprid)) { if (strpos($prid, '{') !== false) { $attributes_check = true; $attributes_ids = ''; $attributes = explode('{', substr($prid, strpos($prid, '{')+1)); for ($i=0, $n=sizeof($attributes); $i<$n; $i++) { $pair = explode('}', $attributes[$i]); if (is_numeric($pair[0]) && is_numeric($pair[1])) { $attributes_ids .= '{' . (int)$pair[0] . '}' . (int)$pair[1]; } else { $attributes_check = false; break; } } if ($attributes_check == true) { $uprid .= $attributes_ids; } } } else { return false; } } return $uprid; } ?>
dsiekiera/modified-bs4
inc/xtc_get_uprid.inc.php
PHP
gpl-2.0
2,442
/* * ZAL - The abstraction layer for Zimbra. * Copyright (C) 2016 ZeXtras S.r.l. * * This file is part of ZAL. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation, version 2 of * the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZAL. If not, see <http://www.gnu.org/licenses/>. */ package org.openzal.zal; import com.zimbra.cs.account.accesscontrol.generated.RightConsts; public class RightConstants { public static String RT_sendAs = RightConsts.RT_sendAs; public static String RT_domainAdminCosRights = RightConsts.RT_domainAdminCosRights; public static String RT_loginAs = RightConsts.RT_loginAs; public static String RT_domainAdminRights = RightConsts.RT_domainAdminRights; public static String RT_adminLoginAs = RightConsts.RT_adminLoginAs; public static String RT_domainAdminConsoleAccountsFeaturesTabRights = RightConsts.RT_domainAdminConsoleAccountsFeaturesTabRights; public static String RT_listZimlet = RightConsts.RT_listZimlet; public static String RT_getZimlet = RightConsts.RT_getZimlet; public static String RT_domainAdminZimletRights = RightConsts.RT_domainAdminZimletRights; public static String RT_setAdminSavedSearch = RightConsts.RT_setAdminSavedSearch; public static String RT_viewAdminSavedSearch = RightConsts.RT_viewAdminSavedSearch; public static String RT_domainAdminConsoleDLSharesTabRights = RightConsts.RT_domainAdminConsoleDLSharesTabRights; public static String RT_getAccountInfo = RightConsts.RT_getAccountInfo; public static String RT_configureQuota = RightConsts.RT_configureQuota; public static String RT_sendOnBehalfOf = RightConsts.RT_sendOnBehalfOf; public static String RT_sendOnBehalfOfDistList = RightConsts.RT_sendOnBehalfOfDistList; public static String RT_sendAsDistList = RightConsts.RT_sendAsDistList; public static String RT_addGroupAlias = RightConsts.RT_addGroupAlias; public static String RT_addGroupMember = RightConsts.RT_addGroupMember; public static String RT_createGroup = RightConsts.RT_createGroup; public static String RT_deleteGroup = RightConsts.RT_deleteGroup; public static String RT_getGroup = RightConsts.RT_getGroup; public static String RT_listGroup = RightConsts.RT_listGroup; public static String RT_modifyGroup = RightConsts.RT_modifyGroup; public static String RT_removeGroupAlias = RightConsts.RT_removeGroupAlias; public static String RT_removeGroupMember = RightConsts.RT_removeGroupMember; public static String RT_renameGroup = RightConsts.RT_renameGroup; }
ZeXtras/OpenZAL
src/java/org/openzal/zal/RightConstants.java
Java
gpl-2.0
2,924
<?php /* +---------------------------------------------------------------------------+ | OpenX v2.8 | | ========== | | | | Copyright (c) 2003-2009 OpenX Limited | | For contact details, see: http://www.openx.org/ | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by | | the Free Software Foundation; either version 2 of the License, or | | (at your option) any later version. | | | | This program is distributed in the hope that it will be useful, | | but WITHOUT ANY WARRANTY; without even the implied warranty of | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | | GNU General Public License for more details. | | | | You should have received a copy of the GNU General Public License | | along with this program; if not, write to the Free Software | | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA | +---------------------------------------------------------------------------+ $Id: userlog-index.php 81439 2012-05-07 23:59:14Z chris.nutting $ */ // Require the initialisation file require_once '../../init.php'; // Required files require_once MAX_PATH . '/lib/max/Admin_DA.php'; require_once MAX_PATH . '/lib/max/other/lib-userlog.inc.php'; require_once MAX_PATH . '/lib/OA/Dal.php'; require_once MAX_PATH . '/lib/OA/Admin/Template.php'; require_once MAX_PATH . '/www/admin/config.php'; require_once MAX_PATH . '/lib/OA/Dll/Audit.php'; require_once MAX_PATH . '/lib/OA/Admin/UI/Field/AuditDaySpanField.php'; require_once 'Pager/Pager.php'; require_once MAX_PATH . '/lib/OX/Translation.php'; // Security check OA_Permission::enforceAccount(OA_ACCOUNT_ADMIN, OA_ACCOUNT_MANAGER, OA_ACCOUNT_ADVERTISER, OA_ACCOUNT_TRAFFICKER); OA_Permission::enforceAccountPermission(OA_ACCOUNT_ADVERTISER, OA_PERM_USER_LOG_ACCESS); OA_Permission::enforceAccountPermission(OA_ACCOUNT_TRAFFICKER, OA_PERM_USER_LOG_ACCESS); // Register input variables $advertiserId = MAX_getValue('advertiserId', 0); $campaignId = MAX_getValue('campaignId', 0); $publisherId = MAX_getValue('publisherId', 0); $zoneId = MAX_getValue('zoneId', 0); $startDate = MAX_getStoredValue('period_start', null); $endDate = MAX_getStoredValue('period_end', null); $periodPreset = MAX_getValue('period_preset', 'all_events'); if (!empty($advertiserId)) { OA_Permission::enforceAccessToObject('clients', $advertiserId); } if (!empty($campaignId)) { OA_Permission::enforceAccessToObject('campaigns', $campaignId); } if (!empty($publisherId)) { OA_Permission::enforceAccessToObject('affiliates', $publisherId); } if (!empty($zoneId)) { OA_Permission::enforceAccessToObject('zones', $zoneId); } /*-------------------------------------------------------*/ /* HTML framework */ /*-------------------------------------------------------*/ phpAds_PageHeader("5.4"); if (OA_Permission::isAccount(OA_ACCOUNT_ADMIN)) { // Show all "My Account" sections phpAds_ShowSections(array("5.1", "5.2", "5.3", "5.5", "5.6", "5.4")); phpAds_UserlogSelection("index"); } else if (OA_Permission::isAccount(OA_ACCOUNT_MANAGER)) { // Show the "Preferences", "User Log" and "Channel Management" sections of the "My Account" sections phpAds_ShowSections(array("5.1", "5.2", "5.4", "5.7")); } else if (OA_Permission::isAccount(OA_ACCOUNT_TRAFFICKER) || OA_Permission::isAccount(OA_ACCOUNT_ADVERTISER)) { phpAds_ShowSections(array("5.1", "5.2", "5.4")); } // Paging related input variables $listorder = htmlspecialchars(MAX_getStoredValue('listorder', 'updated')); $oAudit = &OA_Dal::factoryDO('audit'); $aAuditColumns = $oAudit->table(); $aColumnNamesFound = array_keys($aAuditColumns, $listorder); if (empty($aColumnNamesFound)) { // Invalid column name to order by, set to default $listorder = 'updated'; } $orderdirection = htmlspecialchars(MAX_getStoredValue('orderdirection', 'up')); if (!($orderdirection == 'up' || $orderdirection == 'down')) { if (stristr($orderdirection, 'down')) { $orderdirection = 'down'; } else { $orderdirection = 'up'; } } $setPerPage = MAX_getStoredValue('setPerPage', 10); $pageID = MAX_getStoredValue('pageID', 1); // Setup date selector $aPeriod = array( 'period_preset' => $periodPreset, 'period_start' => $startDate, 'period_end' => $endDate ); $daySpan = new OA_Admin_UI_Audit_DaySpanField('period'); $daySpan->setValueFromArray($aPeriod); $daySpan->enableAutoSubmit(); // Initialize parameters $pageName = basename($_SERVER['SCRIPT_NAME']); // Load template $oTpl = new OA_Admin_Template('userlog-index.html'); // Get advertisers & publishers for filters $showAdvertisers = OA_Permission::isAccount(OA_ACCOUNT_ADVERTISER, OA_ACCOUNT_MANAGER, OA_ACCOUNT_ADMIN); $showPublishers = OA_Permission::isAccount(OA_ACCOUNT_TRAFFICKER, OA_ACCOUNT_MANAGER, OA_ACCOUNT_ADMIN); $agencyId = OA_Permission::getAgencyId(); // Get advertisers if we show them $aAdvertiser = $aPublisher = array(); if ($showAdvertisers) { if (OA_Permission::isAccount(OA_ACCOUNT_ADVERTISER)) { $tempAdvertiserId = OA_Permission::getEntityId(); $aAdvertiserList = Admin_DA::getAdvertisers(array('advertiser_id' => $tempAdvertiserId)); } else { $aAdvertiserList = Admin_DA::getAdvertisers(array('agency_id' => $agencyId)); } $aAdvertiser[0] = $GLOBALS['strSelectAdvertiser']; foreach($aAdvertiserList as $key => $aValue) { $aAdvertiser[$aValue['advertiser_id']] = $aValue['name']; } $aCampaign = array(); if (!empty($advertiserId)) { $campaign = Admin_DA::getCampaigns(array('client_id' => $advertiserId)); $aCampaign[0] = $GLOBALS['strSelectPlacement']; foreach($campaign as $key => $aValue) { $aCampaign[$aValue['campaign_id']] = $aValue['campaignname']; } } } // Get publishers if we show them if ($showPublishers) { if (OA_Permission::isAccount(OA_ACCOUNT_TRAFFICKER)) { $tempPublisherId = OA_Permission::getEntityId(); $aPublisherList = Admin_DA::getPublishers(array('publisher_id' => $tempPublisherId)); } else { $aPublisherList = Admin_DA::getPublishers(array('agency_id' => $agencyId)); } $aPublisher[0] = $GLOBALS['strSelectPublisher']; foreach ($aPublisherList as $key => $aValue) { $aPublisher[$aValue['publisher_id']] = $aValue['name']; } if (!empty($publisherId)) { $zone = Admin_DA::getZones(array('publisher_id' => $publisherId)); $aZone[0] = $GLOBALS['strSelectZone']; foreach ($zone as $key => $aValue) { $aZone[$aValue['zone_id']] = $aValue['name']; } } } $oTrans = new OX_Translation(); $aParams = array( 'order' => $orderdirection, 'listorder' => $listorder, 'start_date' => $startDate, 'end_date' => $endDate, 'prevImg' => '<< ' . $oTrans->translate('Back'), 'nextImg' => $oTrans->translate('Next') . ' >>' ); // Only pass advertiser or website props if we show related checkboxes if ($showAdvertisers) { $aParams['advertiser_id']= $advertiserId; $aParams['campaign_id'] = $campaignId; } if ($showPublishers) { $aParams['publisher_id'] = $publisherId; $aParams['zone_id'] = $zoneId; } // Account security if (OA_Permission::isAccount(OA_ACCOUNT_MANAGER)) { $aParams['account_id'] = OA_Permission::getAccountId(); } if (OA_Permission::isAccount(OA_ACCOUNT_ADVERTISER)) { $aParams['advertiser_account_id'] = OA_Permission::getAccountId(); } if (OA_Permission::isAccount(OA_ACCOUNT_TRAFFICKER)) { $aParams['website_account_id'] = OA_Permission::getAccountId(); } $oUserlog = new OA_Dll_Audit(); $aAuditData = $oUserlog->getAuditLog($aParams); $aParams['totalItems'] = count($aAuditData); if (!isset($pageID) || $pageID == 1) { $aParams['startRecord'] = 0; } else { $aParams['startRecord'] = ($pageID * $setPerPage) - $setPerPage; } if ($aParams['startRecord'] > $aParams['totalItems']) { $aParams['startRecord'] = 0; } $aParams['perPage'] = MAX_getStoredValue('setPerPage', 10); // Retrieve audit details $aAuditData = $oUserlog->getAuditLog($aParams); $pager = & Pager::factory($aParams); $per_page = $pager->_perPage; $pager->history = $pager->getPageData(); $pager->pagerLinks = $pager->getLinks(); $pager->pagerLinks = $pager->pagerLinks['all']; $pager->pagerSelect = preg_replace('/(<select.*?)(>)/i', '$1 onchange="submitForm()" id="setPerPage"$2', $pager->getPerPageSelectBox(10, 100, 10)); // Build column header link params $aAllowdParams = array('advertiserId', 'campaignId', 'publisherId', 'zoneId'); foreach ($aAllowdParams as $key) { if (!empty($$key)) { $aUrlParam[$key] = "$key=".$$key; } } $aUrlParam['listorder'] = "listorder=$listorder"; $aUrlParam['$orderdirection'] = ($orderdirection == 'down') ? "orderdirection=up" : "orderdirection=down"; $urlParam = implode('&', $aUrlParam); // Replace context with translation foreach ($aAuditData as $key => $aValue) { $k = 'str'. str_replace(' ', '', $aValue['context']); if (!empty($GLOBALS[$k])) { $aAuditData[$key]['context'] = $GLOBALS[$k]; } } // Assign vars to template $oTpl->assign('showAdvertisers', $showAdvertisers); $oTpl->assign('showPublishers', $showPublishers); if ($showAdvertisers) { $oTpl->assign('aAdvertiser', $aAdvertiser); $oTpl->assign('aCampaign', $aCampaign); } if ($showPublishers) { $oTpl->assign('aPublisher', $aPublisher); $oTpl->assign('aZone', $aZone); } $oTpl->assign('aAuditEnabled', OA::getConfigOption('audit', 'enabled', false)); $oTpl->assign('aAuditData', $aAuditData); $oTpl->assign('aPeriodPreset', $aPeriodPreset); $oTpl->assign('context', $context); $oTpl->assign('advertiserId', $advertiserId); $oTpl->assign('campaignId', $campaignId); $oTpl->assign('publisherId', $publisherId); $oTpl->assign('zoneId', $zoneId); $oTpl->assign('urlParam', $urlParam); $oTpl->assign('listorder', $listorder); $oTpl->assign('orderdirection', $orderdirection); $oTpl->assign('setPerPage', $setPerPage); $oTpl->assign('pager', $pager); $oTpl->assign('daySpan', $daySpan); // Display page $oTpl->display(); // display footer phpAds_PageFooter(); // Store filter variables in session $session['prefs'][$pageName]['advertiserId'] = $advertiserId; $session['prefs'][$pageName]['campaignId'] = $campaignId; $session['prefs'][$pageName]['publisherId'] = $publisherId; $session['prefs'][$pageName]['zoneId'] = $zoneId; $session['prefs'][$pageName]['period_preset'] = $periodPreset; $seesion['prefs'][$pageName]['setPerPage'] = $setPerPage; $session['prefs'][$pageName]['listorder'] = $listorder; $session['prefs'][$pageName]['orderdirection'] = $orderdirection; phpAds_SessionDataStore(); ?>
soeffing/openx_test
www/admin/userlog-index.php
PHP
gpl-2.0
11,731
<?php class Redux_Validation_url extends Redux_Options { /* for PRO users! - * * Field Constructor. * * Required - must call the parent constructor, then assign field and value to vars, and obviously call the render field function * * @since Redux_Options 1.0.0 */ function __construct($field, $value, $current) { parent::__construct(); $this->field = $field; $this->field['msg'] = (isset($this->field['msg'])) ? $this->field['msg'] : __('You must provide a valid URL for this option.', Redux_TEXT_DOMAIN); $this->value = $value; $this->current = $current; $this->validate(); } /* for PRO users! - * * Field Render Function. * * Takes the vars and validates them * * @since Redux_Options 1.0.0 */ function validate() { if (function_exists('filter_var') && filter_var($this->value, FILTER_VALIDATE_URL) == false) { $this->value = (isset($this->current))?$this->current:''; $this->error = $this->field; } else { $this->value = esc_url_raw($this->value); } } }
EmmaTope/SolidSteps
wp-content/themes/dante/includes/options/validation/url/validation_url.php
PHP
gpl-2.0
1,019
<?php $this->currencies = array ( 'adp' => 'Andorransk peseta', 'aed' => 'Förenade arabemiratens dirham', 'afa' => 'Afghani (1927-2002)', 'afn' => 'Afghani', 'all' => 'Albansk lek', 'amd' => 'Armenisk dram', 'ang' => 'Nederländsk antillisk gulden', 'aoa' => 'Angolansk kwanza', 'aok' => 'Angolansk kwanza (1977-1990)', 'aon' => 'Angolansk ny kwanza (1990-2000)', 'aor' => 'Angolansk kwanza – Reajustado (1995-1999)', 'ara' => 'Argentinsk austral', 'arp' => 'Argentinsk peso (1983-1985)', 'ars' => 'Argentinsk peso', 'ats' => 'Österrikisk schilling', 'aud' => 'Australisk dollar', 'awg' => 'Aruba-florin', 'azm' => 'Azerbajdzjansk manat', 'bad' => 'Bosnisk-hercegovinsk dinar', 'bam' => 'Konvertibel bosnisk-hercegovinsk mark', 'bbd' => 'Barbadisk dollar', 'bdt' => 'Bangladeshisk taka', 'bec' => 'Belgisk franc (konvertibel)', 'bef' => 'Belgisk franc', 'bel' => 'Belgisk franc (finansiell)', 'bgl' => 'Bulgarisk hård lev', 'bgn' => 'Bulgarisk ny lev', 'bhd' => 'Bahrainsk dinar', 'bif' => 'Burundisk franc', 'bmd' => 'Bermuda-dollar', 'bnd' => 'Bruneisk dollar', 'bob' => 'Boliviano', 'bop' => 'Boliviansk peso', 'bov' => 'Boliviansk mvdol', 'brb' => 'Brasiliansk cruzeiro novo (1967-1986)', 'brc' => 'Brasiliansk cruzado', 'bre' => 'Brasiliansk cruzeiro (1990-1993)', 'brl' => 'Brasiliansk real', 'brn' => 'Brasiliansk cruzado novo', 'brr' => 'Brasiliansk cruzeiro', 'bsd' => 'Bahamansk dollar', 'btn' => 'Bhutanesisk ngultrum', 'buk' => 'Burmesisk kyat', 'bwp' => 'Botswansk pula', 'byb' => 'Vitrysk ny rubel (1994-1999)', 'byr' => 'Vitrysk rubel', 'bzd' => 'Belizisk dollar', 'cad' => 'Kanadensisk dollar', 'cdf' => 'Kongolesisk franc congolais', 'che' => 'WIR Euro', 'chf' => 'Schweizisk franc', 'chw' => 'WIR Franc', 'clf' => 'Chilensk unidad de fomento', 'clp' => 'Chilensk peso', 'cny' => 'Kinesisk yuan renminbi', 'cop' => 'Colombiansk peso', 'cou' => 'Unidad de Valor Real', 'crc' => 'Costarikansk colón', 'csd' => 'Serbian Dinar', 'csk' => 'Tjeckisk hård koruna', 'cup' => 'Kubansk peso', 'cve' => 'Kapverdisk escudo', 'cyp' => 'Cypriotiskt pund', 'czk' => 'Tjeckisk koruna', 'ddm' => 'Östtysk mark', 'dem' => 'Tysk mark', 'djf' => 'Djiboutisk franc', 'dkk' => 'Dansk krona', 'dop' => 'Dominikansk peso', 'dzd' => 'Algerisk dinar', 'ecs' => 'Ecuadoriansk sucre', 'ecv' => 'Ecuadoriansk Unidad de Valor Constante (UVC)', 'eek' => 'Estnisk krona', 'egp' => 'Egyptiskt pund', 'eqe' => 'Ekwele', 'ern' => 'Eritreansk nakfa', 'esa' => 'Spanish Peseta (A account)', 'esb' => 'Spanish Peseta (convertible account)', 'esp' => 'Spansk peseta', 'etb' => 'Etiopisk birr', 'eur' => 'Euro', 'fim' => 'Finsk mark', 'fjd' => 'Fijiansk dollar', 'fkp' => 'Falklandsöarnas pund', 'frf' => 'Fransk franc', 'gbp' => 'Brittiskt pund sterling', 'gek' => 'Georgisk kupon larit', 'gel' => 'Georgisk lari', 'ghc' => 'Ghanansk cedi', 'gip' => 'Gibraltiskt pund', 'gmd' => 'Gambisk dalasi', 'gnf' => 'Guineansk franc', 'gns' => 'Guineansk syli', 'gqe' => 'Ekvatorialguineansk ekwele guineana', 'grd' => 'Grekisk drachma', 'gtq' => 'Guatemalansk quetzal', 'gwe' => 'Portugisiska Guinea-escudo', 'gwp' => 'Guinea-Bissau-peso', 'gyd' => 'Guyanansk dollar', 'hkd' => 'Hongkong-dollar', 'hnl' => 'Hoduransk lempira', 'hrd' => 'Kroatisk dinar', 'hrk' => 'Kroatisk kuna', 'htg' => 'Haitisk gourde', 'huf' => 'Ungersk forint', 'idr' => 'Indonesisk rupiah', 'iep' => 'Irländskt pund', 'ilp' => 'Israeliskt pund', 'ils' => 'Israelisk ny shekel', 'inr' => 'Indisk rupie', 'iqd' => 'Irakisk dinar', 'irr' => 'Iransk rial', 'isk' => 'Isländsk krona', 'itl' => 'Italiensk lira', 'jmd' => 'Jamaicansk dollar', 'jod' => 'Jordansk dinar', 'jpy' => 'Japansk yen', 'kes' => 'Kenyansk shilling', 'kgs' => 'Kirgizistansk som', 'khr' => 'Kambodjansk riel', 'kmf' => 'Komorisk franc', 'kpw' => 'Nordkoreansk won', 'krw' => 'Sydkoreansk won', 'kwd' => 'Kuwaitisk dinar', 'kyd' => 'Cayman-dollar', 'kzt' => 'Kazakisk tenge', 'lak' => 'Laotisk kip', 'lbp' => 'Libanesiskt pund', 'lkr' => 'Srilankesisk rupie', 'lrd' => 'Liberisk dollar', 'lsl' => 'Lesothisk loti', 'lsm' => 'Maloti', 'ltl' => 'Lettisk lita', 'ltt' => 'Lettisk talonas', 'luc' => 'Luxembourg Convertible Franc', 'luf' => 'Luxemburgsk franc', 'lul' => 'Luxembourg Financial Franc', 'lvl' => 'Lettisk lats', 'lvr' => 'Lettisk rubel', 'lyd' => 'Libysk dinar', 'mad' => 'Marockansk dirham', 'maf' => 'Marockansk franc', 'mdl' => 'Moldavisk leu', 'mga' => 'Madagaskisk ariary', 'mgf' => 'Madagaskisk franc', 'mkd' => 'Makedonisk denar', 'mlf' => 'Malisk franc', 'mmk' => 'Myanmarisk kyat', 'mnt' => 'Mongolisk tugrik', 'mop' => 'Macaoisk pataca', 'mro' => 'Mauretansk ouguiya', 'mtl' => 'Maltesisk lira', 'mtp' => 'Maltesiskt pund', 'mur' => 'Mauritisk rupie', 'mvr' => 'Maldivisk rufiyaa', 'mwk' => 'Malawisk kwacha', 'mxn' => 'Mexikansk peso', 'mxp' => 'Mexikansk silverpeso (1861-1992)', 'mxv' => 'Mexikansk Unidad de Inversion (UDI)', 'myr' => 'Malaysisk ringgit', 'mze' => 'Moçambikisk escudo', 'mzm' => 'Moçambikisk metical', 'nad' => 'Namibisk dollar', 'ngn' => 'Nigeriansk naira', 'nic' => 'Nicaraguansk córdoba', 'nio' => 'Nicaraguansk córdoba oro', 'nlg' => 'Nederländsk gulden', 'nok' => 'Norsk krona', 'npr' => 'Nepalesisk rupie', 'nzd' => 'Nyzeeländsk dollar', 'omr' => 'Omansk rial', 'pab' => 'Panamansk balboa', 'pei' => 'Peruansk inti', 'pen' => 'Peruansk sol nuevo', 'pes' => 'Peruansk sol', 'pgk' => 'Papuansk kina', 'php' => 'Filippinsk peso', 'pkr' => 'Pakistansk rupie', 'pln' => 'Polsk zloty', 'plz' => 'Polsk zloty (1950-1995)', 'pte' => 'Portugisisk escudo', 'pyg' => 'Paraguaysk guarani', 'qar' => 'Qatarisk rial', 'rhd' => 'Rhodesian Dollar', 'rol' => 'Rumänsk leu', 'ron' => 'Romanian Leu', 'rub' => 'Rysk rubel', 'rur' => 'Rysk rubel (1991-1998)', 'rwf' => 'Rwandisk franc', 'sar' => 'Saudisk riyal', 'sbd' => 'Salomon-dollar', 'scr' => 'Seychellisk rupie', 'sdd' => 'Sudanesisk dinar', 'sdp' => 'Sudanesiskt pund', 'sek' => 'Svensk krona', 'sgd' => 'Singaporiansk dollar', 'shp' => 'S:t Helena-pund', 'sit' => 'Slovensk tolar', 'skk' => 'Slovakisk koruna', 'sll' => 'Sierraleonsk leone', 'sos' => 'Somalisk shilling', 'srd' => 'Surinam Dollar', 'srg' => 'Surinamesisk gulden', 'std' => 'São Tomé och Príncipe-dobra', 'sur' => 'Sovjetisk rubel', 'svc' => 'Salvadoransk colón', 'syp' => 'Syriskt pund', 'szl' => 'Swaziländsk lilangeni', 'thb' => 'Thailändsk baht', 'tjr' => 'Tadzjikisk rubel', 'tjs' => 'Tadzjikisk somoni', 'tmm' => 'Turkmensk manat', 'tnd' => 'Tunisisk dinar', 'top' => 'Tongansk paʻanga', 'tpe' => 'Timoriansk escudo', 'trl' => 'Turkisk lira', 'try' => 'Ny turkisk lira', 'ttd' => 'Trinidadisk dollar', 'twd' => 'Taiwanesisk ny dollar', 'tzs' => 'Tanzanisk shilling', 'uah' => 'Ukrainsk hryvnia', 'uak' => 'Ukrainsk karbovanetz', 'ugs' => 'Ugandisk shilling (1966-1987)', 'ugx' => 'Ugandisk shilling', 'usd' => 'US-dollar', 'usn' => 'US-dollar (nästa dag)', 'uss' => 'US-dollar (samma dag)', 'uyp' => 'Uruguayansk peso (1975-1993)', 'uyu' => 'Uruguayansk peso uruguayo', 'uzs' => 'Uzbekisk sum', 'veb' => 'Venezuelansk bolivar', 'vnd' => 'Vietnamesisk dong', 'vuv' => 'Vanuatisk vatu', 'wst' => 'Västsamoansk tala', 'xaf' => 'CFA Franc BEAC', 'xag' => 'Silver', 'xau' => 'Gold', 'xba' => 'European Composite Unit', 'xbb' => 'European Monetary Unit', 'xbc' => 'European Unit of Account (XBC)', 'xbd' => 'European Unit of Account (XBD)', 'xcd' => 'Östkaribisk dollar', 'xdr' => 'Special Drawing Rights', 'xeu' => 'European Currency Unit', 'xfo' => 'Fransk guldfranc', 'xfu' => 'French UIC-Franc', 'xof' => 'CFA Franc BCEAO', 'xpd' => 'Palladium', 'xpf' => 'CFP-franc', 'xpt' => 'Platinum', 'xre' => 'RINET Funds', 'xts' => 'Testing Currency Code', 'xxx' => 'No Currency', 'ydd' => 'Jemenitisk dinar', 'yer' => 'Jemenitisk rial', 'yud' => 'Jugoslavisk hård dinar', 'yum' => 'Dinar (Serbien och Montenegro)', 'yun' => 'Jugoslavisk konvertibel dinar', 'zal' => 'Sydafrikansk rand (finansiell)', 'zar' => 'Sydafrikansk rand', 'zmk' => 'Zambisk kwacha', 'zrn' => 'Zairisk ny zaire', 'zrz' => 'Zairisk zaire', 'zwd' => 'Zimbabwisk dollar', );
prdatur/soopfw
language/currencies/sv.php
PHP
gpl-2.0
8,556
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ class Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1SubscriberEvent extends Google_Model { protected $customerEventType = 'Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1CustomerEvent'; protected $customerEventDataType = ''; protected $entitlementEventType = 'Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1EntitlementEvent'; protected $entitlementEventDataType = ''; /** * @param Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1CustomerEvent */ public function setCustomerEvent(Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1CustomerEvent $customerEvent) { $this->customerEvent = $customerEvent; } /** * @return Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1CustomerEvent */ public function getCustomerEvent() { return $this->customerEvent; } /** * @param Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1EntitlementEvent */ public function setEntitlementEvent(Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1EntitlementEvent $entitlementEvent) { $this->entitlementEvent = $entitlementEvent; } /** * @return Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1EntitlementEvent */ public function getEntitlementEvent() { return $this->entitlementEvent; } }
palasthotel/grid-wordpress-box-social
vendor/google/apiclient-services/src/Google/Service/Cloudchannel/GoogleCloudChannelV1alpha1SubscriberEvent.php
PHP
gpl-2.0
1,892
<?php /** * content-gallery.php * * The default template for displaying posts with the Gallery post format. * @package Theme_Material * GPL3 Licensed */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <!-- Article header --> <header class="entry-header"> <?php // If single page, display the title // Else, we display the title in a link if ( is_single() ) : ?> <h1><?php the_title(); ?></h1> <?php else : ?> <h1><a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a></h1> <?php endif; ?> <p class="entry-meta"> <?php // Display the meta information material_post_meta(); ?> </p> </header> <!-- end entry-header --> <!-- Article content --> <div class="entry-content"> <?php the_content( __( 'Continue reading &rarr;', 'material' ) ); wp_link_pages(); ?> </div> <!-- end entry-content --> <!-- Article footer --> <footer class="entry-footer"> <?php // If we have a single page and the author bio exists, display it if ( is_single() && get_the_author_meta( 'description' ) ) { echo '<h2>' . __( 'Written by ', 'material' ) . get_the_author() . '</h2>'; echo '<p>' . the_author_meta( 'description' ) . '</p>'; } ?> </footer> <!-- end entry-footer --> </article>
puuga/wordpress
wp-content/themes/material/content-gallery.php
PHP
gpl-2.0
1,286
/* * Copyright (c) 1998-2010 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * Free SoftwareFoundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package javax.jms; /** * The exception */ public class InvalidSelectorException extends JMSException { public InvalidSelectorException(String reason) { super(reason); } public InvalidSelectorException(String reason, String errorCode) { super(reason, errorCode); } }
christianchristensen/resin
modules/jms/src/javax/jms/InvalidSelectorException.java
Java
gpl-2.0
1,322
# exercise from http://www.ling.gu.se/~lager/python_exercises.html # solution from http://rosettacode.org/wiki/99_Bottles_of_Beer#Python # "99 bottle of beer" is a traditional song in the US and Canada. # it is popular to sing on long trips, as it has a very repetitive # format which is easy to memorize, and can take a long time to sing. # the song's simple lyrics are as follows: # 99 bottles of beer on the wall, 99 bottles of beer. # take one down, pass it around, 98 bottles of beer on the wall. # the same verse is repeated, each time with one fewer bottle. # the song is completed when the singers reach zero. # Task now is to write a Python program # capable of generating all the verses of the song. print '------------------------------' print '99 Bottles of Beer on the Wall' print '------------------------------' bottles = 99 song = ''' %d bottles of beer on the wall, %d bottles of beer.\n Take one down, pass it around, %d bottles of beer. ''' for bottles in range(99,0,-1): print song %(bottles,bottles,bottles-1)
SurAnand/pyuthon
99beer.py
Python
gpl-2.0
1,042
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2017 UniPro <ugene@unipro.ru> * http://ugene.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include <U2Core/U2AssemblyUtils.h> #include <U2Core/Log.h> #include "BAMDbiPlugin.h" #include "InvalidFormatException.h" #include "SamReader.h" #include "CigarValidator.h" #include <SamtoolsAdapter.h> namespace U2 { namespace BAM { const int SamReader::LOCAL_READ_BUFFER_SIZE = 100000; Alignment SamReader::parseAlignmentString(QByteArray line) { Alignment alignment; if(line.isEmpty()) { assert(0); throw InvalidFormatException(BAMDbiPlugin::tr("Unexpected empty string")); } QByteArray recordTag; QHash<QByteArray, QByteArray> fields; QList<QByteArray> tokens = line.split('\t'); if (tokens.length() < 11) { throw InvalidFormatException(BAMDbiPlugin::tr("Not enough fields in one of alignments")); } { QByteArray &qname = tokens[0]; // workaround for malformed SAMs if(!QRegExp("[ -~]{1,255}").exactMatch(qname)) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid query template name: %1").arg(QString(qname))); } alignment.setName(qname); } { bool ok = false; int flagsValue = tokens[1].toInt(&ok); if(!ok) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid FLAG value: %1").arg(QString(tokens[1]))); } qint64 flags = 0; if(flagsValue & 0x1) { flags |= Fragmented; } if(flagsValue & 0x2) { flags |= FragmentsAligned; } if(flagsValue & 0x4) { flags |= Unmapped; } if(flagsValue & 0x8) { flags |= NextUnmapped; } if(flagsValue & 0x10) { flags |= Reverse; } if(flagsValue & 0x20) { flags |= NextReverse; } if(flagsValue & 0x40) { flags |= FirstInTemplate; } if(flagsValue & 0x80) { flags |= LastInTemplate; } if(flagsValue & 0x100) { flags |= SecondaryAlignment; } if(flagsValue & 0x200) { flags |= FailsChecks; } if(flagsValue & 0x400) { flags |= Duplicate; } alignment.setFlags(flags); } { QByteArray &rname = tokens[2]; // workaround for malformed SAMs if(!QRegExp("[*]|[!-()+-<>-~][ -~]*").exactMatch(rname)) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid reference name: %1").arg(QString(rname))); } if ("*" == rname) { alignment.setReferenceId(-1); } else { if (!referencesMap.contains(rname)) { throw InvalidFormatException(BAMDbiPlugin::tr("Undefined reference name: %1").arg(QString(rname))); } alignment.setReferenceId(referencesMap[rname]); } } { bool ok = false; int position = tokens[3].toInt(&ok); if(!ok) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid read position value: %1").arg(QString(tokens[3]))); } if(position < 0) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid read position: %1").arg(position)); } alignment.setPosition(position - 1); //to 0-based mapping } { bool ok = false; int mapQuality = tokens[4].toInt(&ok); if(!ok) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid mapping quality value: %1").arg(QString(tokens[4]))); } if(mapQuality < 0 || mapQuality > 255) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid mapping quality: %1").arg(mapQuality)); } alignment.setMapQuality(mapQuality); } { QByteArray &cigarString = tokens[5]; if(!QRegExp("[*]|([0-9]+[MIDNSHPX=])+").exactMatch(cigarString)) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid cigar value: %1").arg(QString(cigarString))); } if ("*" != cigarString) { QString err; QList<U2CigarToken> res = U2AssemblyUtils::parseCigar(cigarString, err); if (!err.isEmpty()) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid cigar value: %1").arg(QString(cigarString))); } QList<Alignment::CigarOperation> cigar; for(int i = 0; i < res.length(); i++) { Alignment::CigarOperation::Operation operation; switch(res[i].op) { case U2CigarOp_M: operation = Alignment::CigarOperation::AlignmentMatch; break; case U2CigarOp_I: operation = Alignment::CigarOperation::Insertion; break; case U2CigarOp_D: operation = Alignment::CigarOperation::Deletion; break; case U2CigarOp_N: operation = Alignment::CigarOperation::Skipped; break; case U2CigarOp_S: operation = Alignment::CigarOperation::SoftClip; break; case U2CigarOp_H: operation = Alignment::CigarOperation::HardClip; break; case U2CigarOp_P: operation = Alignment::CigarOperation::Padding; break; case U2CigarOp_EQ: operation = Alignment::CigarOperation::SequenceMatch; break; case U2CigarOp_X: operation = Alignment::CigarOperation::SequenceMismatch; break; default: throw InvalidFormatException(BAMDbiPlugin::tr("Invalid cigar operation code: %1").arg(res[i].op)); } int operatonLength = res[i].count; cigar.append(Alignment::CigarOperation(operatonLength, operation)); } alignment.setCigar(cigar); } } { QByteArray nextReference = tokens[6]; // workaround for malformed SAMs if(!QRegExp("[*]|[=]|[!-()+-<>-~][ -~]*").exactMatch(nextReference)) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid mate reference name: %1").arg(QString(nextReference))); } if ("*" == nextReference) { alignment.setNextReferenceId(-1); } else if ("=" == nextReference) { alignment.setNextReferenceId(alignment.getReferenceId()); } else { if (!referencesMap.contains(nextReference)) { throw InvalidFormatException(BAMDbiPlugin::tr("Undefined mate reference name: %1").arg(QString(nextReference))); } alignment.setNextReferenceId(referencesMap[nextReference]); } alignment.setNextReferenceName(nextReference); } { bool ok = false; int nextPosition = tokens[7].toInt(&ok); if(!ok) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid mate position value: %1").arg(QString(tokens[7]))); } if(nextPosition < 0) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid mate position: %1").arg(nextPosition)); } alignment.setNextPosition(nextPosition - 1); //to 0-based mapping } { bool ok = false; int templateLength = tokens[8].toInt(&ok); if(!ok) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid template length value: %1").arg(QString(tokens[8]))); } if(!(alignment.getFlags() & Fragmented)) { if(0 != templateLength) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid template length of a single-fragment template: %1").arg(templateLength)); } } alignment.setTemplateLength(templateLength); } { QByteArray sequence = tokens[9]; if(!QRegExp("[*]|[A-Za-z=.]+").exactMatch(sequence)) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid sequence: %1").arg(QString(sequence))); } alignment.setSequence(sequence); } { QByteArray quality = tokens[10]; if ("*" != quality) { if(QRegExp("[!-~]+").exactMatch(quality)) { alignment.setQuality(quality); } } } { QByteArray samAuxString; bool first = true; QMap<QByteArray, QVariant> optionalFields; for (int i = 11; i < tokens.length(); i++) { if (!first) { samAuxString += '\t'; } samAuxString += tokens[i]; first = false; } alignment.setAuxData(SamtoolsAdapter::samString2aux(samAuxString)); } { // Validation of the CIGAR string. int totalLength = 0; int length = alignment.getSequence().length(); const QList<Alignment::CigarOperation> &cigar = alignment.getCigar(); CigarValidator validator(cigar); validator.validate(&totalLength); if(!cigar.isEmpty() && length != totalLength) { const_cast<QList<Alignment::CigarOperation>&>(cigar).clear(); //Ignore invalid cigar } } return alignment; } SamReader::SamReader(IOAdapter &ioAdapter): Reader(ioAdapter), readBuffer(LOCAL_READ_BUFFER_SIZE, '\0') { readHeader(); } const Header &SamReader::getHeader()const { return header; } Alignment SamReader::readAlignment(bool &eof) { QByteArray alignmentString = readString(eof); return parseAlignmentString(alignmentString); } bool SamReader::isEof()const { return ioAdapter.isEof(); } QByteArray SamReader::readString(bool &eof) { char* buff = readBuffer.data(); bool lineOk = false; int len = 0; QByteArray result; while((len = ioAdapter.readLine(buff, LOCAL_READ_BUFFER_SIZE, &lineOk)) == 0) {} if (len == -1) { eof = true; } else { result = QByteArray::fromRawData(buff, len); } return result; } void SamReader::readHeader() { char* buff = readBuffer.data(); bool lineOk = false; int len = 0; qint64 bRead = ioAdapter.bytesRead(); QList<Header::Reference> references; { QList<Header::ReadGroup> readGroups; QList<Header::Program> programs; QList<QByteArray> previousProgramIds; while ((len = ioAdapter.readLine(buff, LOCAL_READ_BUFFER_SIZE, &lineOk)) >= 0) { if(isEof()){ break; } QByteArray line = QByteArray::fromRawData(buff, len); if(line.isEmpty()) { continue; } if(line.startsWith("@CO")) { continue; } if(!line.startsWith('@')) { ioAdapter.skip(bRead - ioAdapter.bytesRead()); break; } bRead = ioAdapter.bytesRead(); QByteArray recordTag; QHash<QByteArray, QByteArray> fields; { QList<QByteArray> tokens = line.split('\t'); recordTag = tokens[0].mid(1); if(!QRegExp("[A-Za-z][A-Za-z]").exactMatch(recordTag)) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid header record tag: %1").arg(QString(recordTag))); } for(int index = 1;index < tokens.size();index++) { QByteArray fieldTag; QByteArray fieldValue; { int colonIndex = tokens[index].indexOf(':'); if(-1 != colonIndex) { fieldTag = tokens[index].mid(0, colonIndex); fieldValue = tokens[index].mid(colonIndex + 1); } else if("PG" == recordTag) { // workaround for invalid headers produced by some programs continue; } else { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid header field: %1").arg(QString(tokens[index]))); } } if(!QRegExp("[A-Za-z][A-Za-z]").exactMatch(fieldTag) && "M5" != fieldTag) { //workaround for bug in the spec throw InvalidFormatException(BAMDbiPlugin::tr("Invalid header field tag: %1").arg(QString(fieldTag))); } // CL and PN tags of can contain any string if(fieldTag!="CL" && fieldTag!="PN" && !QRegExp("[ -~]+").exactMatch(fieldValue)) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid %1-%2 value: %3").arg(QString(recordTag)).arg(QString(fieldTag)).arg(QString(fieldValue))); } if(!fields.contains(fieldTag)) { fields.insert(fieldTag, fieldValue); } else { throw InvalidFormatException(BAMDbiPlugin::tr("Duplicate header field: %1").arg(QString(fieldTag))); } } } if("HD" == recordTag) { if(fields.contains("VN")) { QByteArray value = fields["VN"]; if(!QRegExp("[0-9]+\\.[0-9]+").exactMatch(value)) { //Do nothing to support malformed BAMs //throw InvalidFormatException(BAMDbiPlugin::tr("Invalid HD-VN value: %1").arg(QString(value))); } header.setFormatVersion(Version::parseVersion(value)); } else { throw InvalidFormatException(BAMDbiPlugin::tr("HD record without VN field")); } if(fields.contains("SO")) { QByteArray value = fields["SO"]; if("unknown" == value) { header.setSortingOrder(Header::Unknown); } else if("unsorted" == value) { header.setSortingOrder(Header::Unsorted); } else if("queryname" == value) { header.setSortingOrder(Header::QueryName); } else if("coordinate" == value) { header.setSortingOrder(Header::Coordinate); } else if("sorted" == value) { // workaround for invalid headers produced by some programs header.setSortingOrder(Header::Coordinate); } else { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid HD-SO value: %1").arg(QString(value))); } } else { header.setSortingOrder(Header::Unknown); } } else if("SQ" == recordTag) { Header::Reference *reference = NULL; QByteArray name; if(fields.contains("SN")) { name = fields["SN"]; } else { throw InvalidFormatException(BAMDbiPlugin::tr("SQ record without SN field")); } if(fields.contains("LN")) { QByteArray value = fields["LN"]; bool ok = false; int length = value.toInt(&ok); if(ok) { Header::Reference newRef(name, length); referencesMap.insert(name, references.size()); references.append(newRef); reference = &(references.last()); } else { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid SQ-LN value: %1").arg(QString(value))); } } else { throw InvalidFormatException(BAMDbiPlugin::tr("SQ record without LN field")); } assert(NULL != reference); if(fields.contains("AS")) { reference->setAssemblyId(fields["AS"]); } if(fields.contains("M5")) { QByteArray value = fields["M5"]; //[a-f] is a workaround (not matching to SAM-1.3 spec) to open 1000 Genomes project BAMs if(!QRegExp("[0-9A-Fa-f]+").exactMatch(value)) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid SQ-M5 value: %1").arg(QString(value))); } reference->setMd5(fields["M5"]); } if(fields.contains("SP")) { reference->setSpecies(fields["SP"]); } if(fields.contains("UR")) { reference->setUri(fields["UR"]); } } else if("RG" == recordTag) { Header::ReadGroup readGroup; if(fields.contains("ID")) { QByteArray value = fields["SN"]; readGroupsMap.insert(value, readGroups.size()); } else { fields.insert("ID", "-1"); } if(fields.contains("CN")) { readGroup.setSequencingCenter(fields["CN"]); } if(fields.contains("DS")) { readGroup.setDescription(fields["DS"]); } if(fields.contains("DT")) { QByteArray value = fields["DT"]; QDateTime dateTime = QDateTime::fromString(value, Qt::ISODate); if(dateTime.isValid()) { readGroup.setDate(dateTime); } else { QDate date = QDate::fromString(value, Qt::ISODate); if(date.isValid()) { readGroup.setDate(date); } else { //Allow anything. //throw InvalidFormatException(BAMDbiPlugin::tr("Invalid RG-DT field value: %1").arg(QString(value))); } } } if(fields.contains("LB")) { readGroup.setLibrary(fields["LB"]); } if(fields.contains("PG")) { readGroup.setPrograms(fields["PG"]); } if(fields.contains("PI")) { QByteArray value = fields["PI"]; bool ok = false; int predictedInsertSize = value.toInt(&ok); if(ok) { readGroup.setPredictedInsertSize(predictedInsertSize); } else { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid RG-PI field value: %1").arg(QString(value))); } } if(fields.contains("PL")) { readGroup.setPlatform(fields["PL"]); } if(fields.contains("PU")) { readGroup.setPlatformUnit(fields["PU"]); } if(fields.contains("SM")) { readGroup.setSample(fields["SM"]); } readGroups.append(readGroup); } else if("PG" == recordTag) { Header::Program program; if(!fields.contains("ID")) { fields.insert("ID", QByteArray::number(programs.size())); } programsMap.insert(fields["ID"], programs.size()); if(fields.contains("PN")) { program.setName(fields["PN"]); } if(fields.contains("CL")) { program.setCommandLine(fields["CL"]); } if(fields.contains("PP")) { previousProgramIds.append(fields["PP"]); } else { previousProgramIds.append(QByteArray()); } if(fields.contains("VN")) { program.setVersion(fields["VN"]); } programs.append(program); } } for(int index = 0;index < programs.size();index++) { const QByteArray &previousProgramId = previousProgramIds[index]; if(!previousProgramId.isEmpty()) { if(programsMap.contains(previousProgramId)) { programs[index].setPreviousId(programsMap[previousProgramId]); } else { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid PG-PP field value: %1").arg(QString(previousProgramId))); } } } header.setReferences(references); header.setReadGroups(readGroups); header.setPrograms(programs); } } } // namespace BAM } // namespace U2
mfursov/ugene
src/plugins/dbi_bam/src/SamReader.cpp
C++
gpl-2.0
21,739
package com.code.taskmanager.bean; import android.graphics.drawable.Drawable; public class AppInfo { public Drawable icon; public String name; public String packagename; public boolean sysApp; public long mem; }
silvernoo/KillTask
src/com/code/taskmanager/bean/AppInfo.java
Java
gpl-2.0
219
##################################################################### # -*- coding: iso-8859-1 -*- # # # # Frets on Fire # # Copyright (C) 2006 Sami Kyostila # # 2008 Alarian # # 2008 myfingershurt # # 2008 Capo # # 2008 Glorandwarf # # 2008 QQStarS # # 2008 Blazingamer # # 2008 evilynux <evilynux@gmail.com> # # # # This program is free software; you can redistribute it and/or # # modify it under the terms of the GNU General Public License # # as published by the Free Software Foundation; either version 2 # # of the License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program; if not, write to the Free Software # # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # # MA 02110-1301, USA. # ##################################################################### from Song import Note, Tempo from Mesh import Mesh from Neck import Neck import random from copy import deepcopy from Shader import shaders from OpenGL.GL import * import math #myfingershurt: needed for multi-OS file fetching import os import Log import Song #need the base song defines as well from Instrument import * class Guitar(Instrument): def __init__(self, engine, playerObj, editorMode = False, player = 0, bass = False): Instrument.__init__(self, engine, playerObj, player) self.isDrum = False self.isBassGuitar = bass self.isVocal = False self.debugMode = False self.gameMode2p = self.engine.world.multiMode self.matchingNotes = [] self.starSpinFrameIndex = 0 self.starSpinFrames = 16 self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: Log.debug("Guitar class init...") #death_au: fixed neck size #if self.engine.theme.twoDnote == False or self.engine.theme.twoDkeys == False: #self.boardWidth = 3.6 #self.boardLength = 9.0 self.lastPlayedNotes = [] #MFH - for reverting when game discovers it implied incorrectly self.missedNotes = [] self.missedNoteNums = [] self.editorMode = editorMode #########For Animations self.Animspeed = 30#Lower value = Faster animations #For Animated Starnotes self.indexCount = 0 #Alarian, For animated hitglow self.HCountAni = False #myfingershurt: self.hopoStyle = self.engine.config.get("game", "hopo_system") self.gh2sloppy = self.engine.config.get("game", "gh2_sloppy") if self.gh2sloppy == 1: self.hopoStyle = 4 self.sfxVolume = self.engine.config.get("audio", "SFX_volume") #blazingamer self.killfx = self.engine.config.get("performance", "killfx") self.killCount = 0 self.bigMax = 1 #Get theme themename = self.engine.data.themeLabel #now theme determination logic is only in data.py: self.theme = self.engine.data.theme self.oFlash = None #myfingershurt: self.bassGrooveNeckMode = self.engine.config.get("game", "bass_groove_neck") self.starspin = self.engine.config.get("performance", "starspin") if self.twoDnote == True: #Spinning starnotes or not? #myfingershurt: allowing any non-Rock Band theme to have spinning starnotes if the SpinNotes.png is available in that theme's folder if self.starspin == True and self.theme < 2: #myfingershurt: check for SpinNotes, if not there then no animation if self.gameMode2p == 6: if engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"spinnotesbattle.png")): self.starSpinFrames = 8 else: self.starspin = False if not engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notesbattle.png")): engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notes.png")) else: if not engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"spinnotes.png")): self.starspin = False engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notes.png")) else: if self.gameMode2p == 6: if not engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notesbattle.png")): engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notes.png")) else: engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notes.png")) #mfh - adding fallback for beta option else: #MFH - can't use IOError for fallback logic for a Mesh() call... if self.engine.fileExists(os.path.join("themes", themename, "note.dae")): engine.resource.load(self, "noteMesh", lambda: Mesh(engine.resource.fileName("themes", themename, "note.dae"))) else: engine.resource.load(self, "noteMesh", lambda: Mesh(engine.resource.fileName("note.dae"))) for i in range(5): if engine.loadImgDrawing(self, "notetex"+chr(97+i), os.path.join("themes", themename, "notetex_"+chr(97+i)+".png")): self.notetex = True else: self.notetex = False break if self.engine.fileExists(os.path.join("themes", themename, "star.dae")): engine.resource.load(self, "starMesh", lambda: Mesh(engine.resource.fileName("themes", themename, "star.dae"))) else: self.starMesh = None for i in range(5): if engine.loadImgDrawing(self, "startex"+chr(97+i), os.path.join("themes", themename, "startex_"+chr(97+i)+".png")): self.startex = True else: self.startex = False break for i in range(5): if engine.loadImgDrawing(self, "staratex"+chr(97+i), os.path.join("themes", themename, "staratex_"+chr(97+i)+".png")): self.staratex = True else: self.staratex = False break if self.gameMode2p == 6: if not engine.loadImgDrawing(self, "battleFrets", os.path.join("themes", themename,"battle_frets.png")): self.battleFrets = None if self.twoDkeys == True: engine.loadImgDrawing(self, "fretButtons", os.path.join("themes",themename,"fretbuttons.png")) else: defaultKey = False #MFH - can't use IOError for fallback logic for a Mesh() call... if self.engine.fileExists(os.path.join("themes", themename, "key.dae")): engine.resource.load(self, "keyMesh", lambda: Mesh(engine.resource.fileName("themes", themename, "key.dae"))) else: engine.resource.load(self, "keyMesh", lambda: Mesh(engine.resource.fileName("key.dae"))) defaultKey = True if defaultKey: self.keytex = False else: for i in range(5): if engine.loadImgDrawing(self, "keytex"+chr(97+i), os.path.join("themes", themename, "keytex_"+chr(97+i)+".png")): self.keytex = True else: self.keytex = False break #inkk: loading theme-dependant tail images #myfingershurt: must ensure the new tails don't affect the Rock Band mod... self.simpleTails = False for i in range(0,7): if not engine.loadImgDrawing(self, "tail"+str(i), os.path.join("themes",themename,"tails","tail"+str(i)+".png"), textureSize = (128, 128)): self.simpleTails = True break if not engine.loadImgDrawing(self, "taile"+str(i), os.path.join("themes",themename,"tails","taile"+str(i)+".png"), textureSize = (128, 128)): self.simpleTails = True break if not engine.loadImgDrawing(self, "btail"+str(i), os.path.join("themes",themename,"tails","btail"+str(i)+".png"), textureSize = (128, 128)): self.simpleTails = True break if not engine.loadImgDrawing(self, "btaile"+str(i), os.path.join("themes",themename,"tails","btaile"+str(i)+".png"), textureSize = (128, 128)): self.simpleTails = True break if self.simpleTails: Log.debug("Simple tails used; complex tail loading error...") if not engine.loadImgDrawing(self, "tail1", os.path.join("themes",themename,"tail1.png"), textureSize = (128, 128)): engine.loadImgDrawing(self, "tail1", "tail1.png", textureSize = (128, 128)) if not engine.loadImgDrawing(self, "tail2", os.path.join("themes",themename,"tail2.png"), textureSize = (128, 128)): engine.loadImgDrawing(self, "tail2", "tail2.png", textureSize = (128, 128)) if not engine.loadImgDrawing(self, "bigTail1", os.path.join("themes",themename,"bigtail1.png"), textureSize = (128, 128)): engine.loadImgDrawing(self, "bigTail1", "bigtail1.png", textureSize = (128, 128)) if not engine.loadImgDrawing(self, "bigTail2", os.path.join("themes",themename,"bigtail2.png"), textureSize = (128, 128)): engine.loadImgDrawing(self, "bigTail2", "bigtail2.png", textureSize = (128, 128)) if not engine.loadImgDrawing(self, "kill1", os.path.join("themes", themename, "kill1.png"), textureSize = (128, 128)): engine.loadImgDrawing(self, "kill1", "kill1.png", textureSize = (128, 128)) if not engine.loadImgDrawing(self, "kill2", os.path.join("themes", themename, "kill2.png"), textureSize = (128, 128)): engine.loadImgDrawing(self, "kill2", "kill2.png", textureSize = (128, 128)) #MFH - freestyle tails (for drum fills & BREs) if not engine.loadImgDrawing(self, "freestyle1", os.path.join("themes", themename, "freestyletail1.png"), textureSize = (128, 128)): engine.loadImgDrawing(self, "freestyle1", "freestyletail1.png", textureSize = (128, 128)) if not engine.loadImgDrawing(self, "freestyle2", os.path.join("themes", themename, "freestyletail2.png"), textureSize = (128, 128)): engine.loadImgDrawing(self, "freestyle2", "freestyletail2.png", textureSize = (128, 128)) self.twoChordMax = False self.rockLevel = 0.0 self.neck = Neck(self.engine, self, playerObj) def selectPreviousString(self): self.selectedString = (self.selectedString - 1) % self.strings def selectString(self, string): self.selectedString = string % self.strings def selectNextString(self): self.selectedString = (self.selectedString + 1) % self.strings def noteBeingHeld(self): noteHeld = False for i in range(0,5): if self.hit[i] == True: noteHeld = True return noteHeld def isKillswitchPossible(self): possible = False for i in range(0,5): if self.hit[i] == True: possible = True return possible def renderTail(self, length, sustain, kill, color, flat = False, tailOnly = False, isTappable = False, big = False, fret = 0, spNote = False, freestyleTail = 0, pos = 0): #volshebnyi - if freestyleTail == 0, act normally. # if freestyleTail == 1, render an freestyle tail # if freestyleTail == 2, render highlighted freestyle tail if not self.simpleTails:#Tail Colors tailcol = (1,1,1, color[3]) else: if big == False and tailOnly == True: tailcol = (.6, .6, .6, color[3]) else: tailcol = (color) #volshebnyi - tail color when sp is active if self.starPowerActive and self.theme != 2 and not color == (0,0,0,1):#8bit c = self.fretColors[5] tailcol = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], color[3]) if flat: tailscale = (1, .1, 1) else: tailscale = None if sustain: if not length == None: size = (.08, length) if size[1] > self.boardLength: s = self.boardLength else: s = length # if freestyleTail == 1, render freestyle tail if freestyleTail == 0: #normal tail rendering #myfingershurt: so any theme containing appropriate files can use new tails if not self.simpleTails: if big == True and tailOnly == True: if kill and self.killfx == 0: zsize = .25 tex1 = self.kill1 tex2 = self.kill2 #volshebnyi - killswitch tail width and color change kEffect = ( math.sin( pos / 50 ) + 1 ) /2 size = (0.02+kEffect*0.15, s - zsize) c = [self.killColor[0],self.killColor[1],self.killColor[2]] if c != [0,0,0]: for i in range(0,3): c[i]=c[i]*kEffect+color[i]*(1-kEffect) tailcol = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1) else: zsize = .25 size = (.17, s - zsize) if self.starPowerActive and not color == (0,0,0,1): tex1 = self.btail6 tex2 = self.btaile6 else: if fret == 0: tex1 = self.btail1 tex2 = self.btaile1 elif fret == 1: tex1 = self.btail2 tex2 = self.btaile2 elif fret == 2: tex1 = self.btail3 tex2 = self.btaile3 elif fret == 3: tex1 = self.btail4 tex2 = self.btaile4 elif fret == 4: tex1 = self.btail5 tex2 = self.btaile5 else: zsize = .15 size = (.1, s - zsize) if tailOnly:#Note let go tex1 = self.tail0 tex2 = self.taile0 else: if self.starPowerActive and not color == (0,0,0,1): tex1 = self.tail6 tex2 = self.taile6 else: if fret == 0: tex1 = self.tail1 tex2 = self.taile1 elif fret == 1: tex1 = self.tail2 tex2 = self.taile2 elif fret == 2: tex1 = self.tail3 tex2 = self.taile3 elif fret == 3: tex1 = self.tail4 tex2 = self.taile4 elif fret == 4: tex1 = self.tail5 tex2 = self.taile5 else: if big == True and tailOnly == True: if kill: zsize = .25 tex1 = self.kill1 tex2 = self.kill2 #volshebnyi - killswitch tail width and color change kEffect = ( math.sin( pos / 50 ) + 1 ) /2 size = (0.02+kEffect*0.15, s - zsize) c = [self.killColor[0],self.killColor[1],self.killColor[2]] if c != [0,0,0]: for i in range(0,3): c[i]=c[i]*kEffect+color[i]*(1-kEffect) tailcol = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1) else: zsize = .25 size = (.11, s - zsize) tex1 = self.bigTail1 tex2 = self.bigTail2 else: zsize = .15 size = (.08, s - zsize) tex1 = self.tail1 tex2 = self.tail2 else: #freestyleTail > 0 # render an inactive freestyle tail (self.freestyle1 & self.freestyle2) zsize = .25 if self.freestyleActive: size = (.30, s - zsize) #was .15 else: size = (.15, s - zsize) tex1 = self.freestyle1 tex2 = self.freestyle2 if freestyleTail == 1: #glColor4f(*color) c1, c2, c3, c4 = color tailGlow = 1 - (pos - self.freestyleLastFretHitTime[fret] ) / self.freestylePeriod if tailGlow < 0: tailGlow = 0 color = (c1 + c1*2.0*tailGlow, c2 + c2*2.0*tailGlow, c3 + c3*2.0*tailGlow, c4*0.6 + c4*0.4*tailGlow) #MFH - this fades inactive tails' color darker tailcol = (color) if self.theme == 2 and freestyleTail == 0 and big and tailOnly and shaders.enable("tail"): color = (color[0]*1.5,color[1]*1.5,color[2]*1.5,1.0) shaders.setVar("color",color) if kill and self.killfx == 0: h = shaders.getVar("height") shaders.modVar("height",0.5,0.06/h-0.1) shaders.setVar("offset",(5.0-size[1],0.0)) size=(size[0]*15,size[1]) self.engine.draw3Dtex(tex1, vertex = (-size[0], 0, size[0], size[1]), texcoord = (0.0, 0.0, 1.0, 1.0), scale = tailscale, color = tailcol) self.engine.draw3Dtex(tex2, vertex = (-size[0], size[1], size[0], size[1] + (zsize)), scale = tailscale, texcoord = (0.0, 0.05, 1.0, 0.95), color = tailcol) shaders.disable() #MFH - this block of code renders the tail "beginning" - before the note, for freestyle "lanes" only #volshebnyi if freestyleTail > 0 and pos < self.freestyleStart + self.freestyleLength: self.engine.draw3Dtex(tex2, vertex = (-size[0], 0-(zsize), size[0], 0 + (.05)), scale = tailscale, texcoord = (0.0, 0.95, 1.0, 0.05), color = tailcol) if tailOnly: return def renderNote(self, length, sustain, kill, color, flat = False, tailOnly = False, isTappable = False, big = False, fret = 0, spNote = False): if flat: glScalef(1, .1, 1) if tailOnly: return if self.twoDnote == True: #myfingershurt: this should be retrieved once at init, not repeatedly in-game whenever tails are rendered. if self.notedisappear == True:#Notes keep on going when missed notecol = (1,1,1)#capo else: if flat:#Notes disappear when missed notecol = (.1,.1,.1) else: notecol = (1,1,1) tailOnly == True if self.theme < 2: if self.starspin: size = (self.boardWidth/self.strings/2, self.boardWidth/self.strings/2) texSize = (fret/5.0,fret/5.0+0.2) if spNote == True: if isTappable: texY = (0.150+self.starSpinFrameIndex*0.05, 0.175+self.starSpinFrameIndex*0.05) else: texY = (0.125+self.starSpinFrameIndex*0.05, 0.150+self.starSpinFrameIndex*0.05) else: if isTappable: texY = (0.025,0.05) else: texY = (0,0.025) if self.starPowerActive: texY = (0.10,0.125) #QQstarS if isTappable: texSize = (0.2,0.4) else: texSize = (0,0.2) else: size = (self.boardWidth/self.strings/2, self.boardWidth/self.strings/2) texSize = (fret/5.0,fret/5.0+0.2) if spNote == True: if isTappable: texY = (0.6, 0.8) else: texY = (0.4,0.6) else: if isTappable: texY = (0.2,0.4) else: texY = (0,0.2) if self.starPowerActive: texY = (0.8,1) if isTappable: texSize = (0.2,0.4) else: texSize = (0,0.2) elif self.theme == 2: size = (self.boardWidth/self.strings/2, self.boardWidth/self.strings/2) texSize = (fret/5.0,fret/5.0+0.2) if spNote == True: if isTappable: texY = (3*0.166667, 4*0.166667) else: texY = (2*0.166667, 3*0.166667) else: if isTappable: texY = (1*0.166667, 2*0.166667) else: texY = (0, 1*0.166667) #myfingershurt: adding spNote==False conditional so that star notes can appear in overdrive if self.starPowerActive and spNote == False: if isTappable: texY = (5*0.166667, 1) else: texY = (4*0.166667, 5*0.166667) self.engine.draw3Dtex(self.noteButtons, vertex = (-size[0],size[1],size[0],-size[1]), texcoord = (texSize[0],texY[0],texSize[1],texY[1]), scale = (1,1,0), rot = (30,1,0,0), multiples = True, color = color, vertscale = .27) else: shaders.setVar("Material",color,"notes") #mesh = outer ring (black) #mesh_001 = main note (key color) #mesh_002 = top (spot or hopo if no mesh_003) #mesh_003 = hopo bump (hopo color) if spNote == True and self.starMesh is not None: meshObj = self.starMesh else: meshObj = self.noteMesh glPushMatrix() glEnable(GL_DEPTH_TEST) glDepthMask(1) glShadeModel(GL_SMOOTH) if self.noterotate: glRotatef(90, 0, 1, 0) glRotatef(-90, 1, 0, 0) if spNote == True and self.threeDspin == True: glRotate(90 + self.time/3, 0, 1, 0) #death_au: fixed 3D note colours #volshebnyi - note color when sp is active glColor4f(*color) if self.starPowerActive and self.theme != 2 and not color == (0,0,0,1): c = self.fretColors[5] glColor4f(.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1) if fret == 0: # green note glRotate(self.engine.theme.noterot[0], 0, 0, 1), glTranslatef(0, self.engine.theme.notepos[0], 0) elif fret == 1: # red note glRotate(self.engine.theme.noterot[1], 0, 0, 1), glTranslatef(0, self.engine.theme.notepos[1], 0) elif fret == 2: # yellow glRotate(self.engine.theme.noterot[2], 0, 0, 1), glTranslatef(0, self.engine.theme.notepos[2], 0) elif fret == 3:# blue note glRotate(self.engine.theme.noterot[3], 0, 0, 1), glTranslatef(0, self.engine.theme.notepos[3], 0) elif fret == 4:# blue note glRotate(self.engine.theme.noterot[4], 0, 0, 1), glTranslatef(0, self.engine.theme.notepos[4], 0) if self.staratex == True and self.starPowerActive and spNote == False: glColor3f(1,1,1) glEnable(GL_TEXTURE_2D) getattr(self,"staratex"+chr(97+fret)).texture.bind() glMatrixMode(GL_TEXTURE) glScalef(1, -1, 1) glMatrixMode(GL_MODELVIEW) glScalef(self.boardScaleX, self.boardScaleY, 1) if isTappable: mesh = "Mesh_001" else: mesh = "Mesh" meshObj.render(mesh) if shaders.enable("notes"): shaders.setVar("isTextured",True) meshObj.render(mesh) shaders.disable() glMatrixMode(GL_TEXTURE) glLoadIdentity() glMatrixMode(GL_MODELVIEW) glDisable(GL_TEXTURE_2D) elif self.notetex == True and spNote == False: glColor3f(1,1,1) glEnable(GL_TEXTURE_2D) getattr(self,"notetex"+chr(97+fret)).texture.bind() glMatrixMode(GL_TEXTURE) glScalef(1, -1, 1) glMatrixMode(GL_MODELVIEW) glScalef(self.boardScaleX, self.boardScaleY, 1) if isTappable: mesh = "Mesh_001" else: mesh = "Mesh" meshObj.render(mesh) if shaders.enable("notes"): shaders.setVar("isTextured",True) meshObj.render(mesh) shaders.disable() glMatrixMode(GL_TEXTURE) glLoadIdentity() glMatrixMode(GL_MODELVIEW) glDisable(GL_TEXTURE_2D) elif self.startex == True and spNote == True: glColor3f(1,1,1) glEnable(GL_TEXTURE_2D) getattr(self,"startex"+chr(97+fret)).texture.bind() glMatrixMode(GL_TEXTURE) glScalef(1, -1, 1) glMatrixMode(GL_MODELVIEW) glScalef(self.boardScaleX, self.boardScaleY, 1) if isTappable: mesh = "Mesh_001" else: mesh = "Mesh" meshObj.render(mesh) if shaders.enable("notes"): shaders.setVar("isTextured",True) meshObj.render(mesh) shaders.disable() glMatrixMode(GL_TEXTURE) glLoadIdentity() glMatrixMode(GL_MODELVIEW) glDisable(GL_TEXTURE_2D) else: if shaders.enable("notes"): shaders.setVar("isTextured",False) meshObj.render("Mesh_001") shaders.disable() glColor3f(self.spotColor[0], self.spotColor[1], self.spotColor[2]) if isTappable: if self.hopoColor[0] == -2: glColor4f(*color) else: glColor3f(self.hopoColor[0], self.hopoColor[1], self.hopoColor[2]) if(meshObj.find("Mesh_003")) == True: meshObj.render("Mesh_003") glColor3f(self.spotColor[0], self.spotColor[1], self.spotColor[2]) meshObj.render("Mesh_002") glColor3f(self.meshColor[0], self.meshColor[1], self.meshColor[2]) meshObj.render("Mesh") glDepthMask(0) glPopMatrix() def renderFreestyleLanes(self, visibility, song, pos): if not song: return if not song.readyToGo: return #boardWindowMin = pos - self.currentPeriod * 2 boardWindowMax = pos + self.currentPeriod * self.beatsPerBoard track = song.midiEventTrack[self.player] #MFH - render 5 freestyle tails when Song.freestyleMarkingNote comes up if self.freestyleEnabled: freestyleActive = False #for time, event in track.getEvents(boardWindowMin, boardWindowMax): for time, event in track.getEvents(pos - self.freestyleOffset , boardWindowMax + self.freestyleOffset): if isinstance(event, Song.MarkerNote): if event.number == Song.freestyleMarkingNote: length = (event.length - 50) / self.currentPeriod / self.beatsPerUnit w = self.boardWidth / self.strings self.freestyleLength = event.length #volshebnyi self.freestyleStart = time # volshebnyi z = ((time - pos) / self.currentPeriod) / self.beatsPerUnit z2 = ((time + event.length - pos) / self.currentPeriod) / self.beatsPerUnit if z > self.boardLength * .8: f = (self.boardLength - z) / (self.boardLength * .2) elif z < 0: f = min(1, max(0, 1 + z2)) else: f = 1.0 #MFH - must extend the tail past the first fretboard section dynamically so we don't have to render the entire length at once #volshebnyi - allow tail to move under frets if time - self.freestyleOffset < pos: freestyleActive = True if z < -1.5: length += z +1.5 z = -1.5 #MFH - render 5 freestyle tails for theFret in range(0,5): x = (self.strings / 2 - theFret) * w c = self.fretColors[theFret] color = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1 * visibility * f) glPushMatrix() glTranslatef(x, (1.0 - visibility) ** (theFret + 1), z) freestyleTailMode = 1 self.renderTail(length, sustain = True, kill = False, color = color, flat = False, tailOnly = True, isTappable = False, big = True, fret = theFret, spNote = False, freestyleTail = freestyleTailMode, pos = pos) glPopMatrix() self.freestyleActive = freestyleActive def renderNotes(self, visibility, song, pos, killswitch): if not song: return if not song.readyToGo: return # Update dynamic period self.currentPeriod = self.neckSpeed #self.targetPeriod = self.neckSpeed self.killPoints = False w = self.boardWidth / self.strings track = song.track[self.player] num = 0 enable = True starEventsInView = False renderedNotes = reversed(self.getRequiredNotesForRender(song,pos)) for time, event in renderedNotes: #for time, event in reversed(track.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard)): #MFH - reverse order of note rendering if isinstance(event, Tempo): self.tempoBpm = event.bpm if self.lastBpmChange > 0 and self.disableVBPM == True: continue if (pos - time > self.currentPeriod or self.lastBpmChange < 0) and time > self.lastBpmChange: self.baseBeat += (time - self.lastBpmChange) / self.currentPeriod self.targetBpm = event.bpm self.lastBpmChange = time self.neck.lastBpmChange = time self.neck.baseBeat = self.baseBeat # self.setBPM(self.targetBpm) # glorandwarf: was setDynamicBPM(self.targetBpm) continue if not isinstance(event, Note): continue if (event.noteBpm == 0.0): event.noteBpm = self.tempoBpm if self.coOpFailed: if self.coOpRestart: if time - self.coOpRescueTime < (self.currentPeriod * self.beatsPerBoard * 2): continue elif self.coOpRescueTime + (self.currentPeriod * self.beatsPerBoard * 2) < pos: self.coOpFailed = False self.coOpRestart = False Log.debug("Turning off coOpFailed. Rescue successful.") else: continue #can't break. Tempo. c = self.fretColors[event.number] x = (self.strings / 2 - event.number) * w z = ((time - pos) / self.currentPeriod) / self.beatsPerUnit z2 = ((time + event.length - pos) / self.currentPeriod) / self.beatsPerUnit if z > self.boardLength * .8: f = (self.boardLength - z) / (self.boardLength * .2) elif z < 0: f = min(1, max(0, 1 + z2)) else: f = 1.0 #volshebnyi - hide notes in BRE zone if BRE enabled if self.freestyleEnabled and self.freestyleStart > 0: if time >= self.freestyleStart-self.freestyleOffset and time < self.freestyleStart + self.freestyleLength+self.freestyleOffset: z = -2.0 if self.twoDnote == True and not self.useFretColors: color = (1,1,1, 1 * visibility * f) else: color = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1 * visibility * f) if event.length > 120: length = (event.length - 50) / self.currentPeriod / self.beatsPerUnit else: length = 0 flat = False tailOnly = False spNote = False #myfingershurt: user setting for starpower refill / replenish notes if self.starPowerActive: if self.spRefillMode == 0: #mode 0 = no starpower / overdrive refill notes self.spEnabled = False elif self.spRefillMode == 1 and self.theme != 2: #mode 1 = overdrive refill notes in RB themes only self.spEnabled = False elif self.spRefillMode == 2 and song.midiStyle != 1: #mode 2 = refill based on MIDI type self.spEnabled = False if event.star: #self.isStarPhrase = True starEventsInView = True if event.finalStar: self.finalStarSeen = True starEventsInView = True if event.star and self.spEnabled: spNote = True if event.finalStar and self.spEnabled: spNote = True if event.played or event.hopod: if event.flameCount < 1 and not self.starPowerGained: Log.debug("star power added") if self.gameMode2p == 6: if self.battleSuddenDeath: self.battleObjects = [1] + self.battleObjects[:2] else: self.battleObjects = [self.battleObjectsEnabled[random.randint(0,len(self.battleObjectsEnabled)-1)]] + self.battleObjects[:2] self.battleGetTime = pos self.battleObjectGained = True Log.debug("Battle Object Gained, Objects %s" % str(self.battleObjects)) else: if self.starPower < 100: self.starPower += 25 if self.starPower > 100: self.starPower = 100 self.neck.overdriveFlashCount = 0 #MFH - this triggers the oFlash strings & timer self.starPowerGained = True if event.tappable < 2: isTappable = False else: isTappable = True # Clip the played notes to the origin #myfingershurt: this should be loaded once at init, not every render... if self.notedisappear == True:#Notes keep on going when missed ###Capo### if event.played or event.hopod: tailOnly = True length += z z = 0 if length <= 0: continue if z < 0 and not (event.played or event.hopod): color = (.6, .6, .6, .5 * visibility * f) flat = True ###endCapo### else:#Notes disappear when missed if z < 0: if event.played or event.hopod: tailOnly = True length += z z = 0 if length <= 0: continue else: color = (.6, .6, .6, .5 * visibility * f) flat = True big = False self.bigMax = 0 for i in range(0,5): if self.hit[i]: big = True self.bigMax += 1 #MFH - filter out this tail whitening when starpower notes have been disbled from a screwup if self.spEnabled and killswitch: if event.star or event.finalStar: if big == True and tailOnly == True: self.killPoints = True color = (1,1,1,1) if z + length < -1.0: continue if event.length <= 120: length = None sustain = False if event.length > (1.4 * (60000.0 / event.noteBpm) / 4): sustain = True glPushMatrix() glTranslatef(x, (1.0 - visibility) ** (event.number + 1), z) if shaders.turnon: shaders.setVar("note_position",(x, (1.0 - visibility) ** (event.number + 1), z),"notes") if self.battleStatus[8]: renderNote = random.randint(0,2) else: renderNote = 0 if renderNote == 0: if big == True and num < self.bigMax: num += 1 self.renderNote(length, sustain = sustain, kill = killswitch, color = color, flat = flat, tailOnly = tailOnly, isTappable = isTappable, big = True, fret = event.number, spNote = spNote) else: self.renderNote(length, sustain = sustain, kill = killswitch, color = color, flat = flat, tailOnly = tailOnly, isTappable = isTappable, fret = event.number, spNote = spNote) glPopMatrix() if (not starEventsInView and self.finalStarSeen): self.spEnabled = True self.finalStarSeen = False self.isStarPhrase = False def renderTails(self, visibility, song, pos, killswitch): if not song: return if not song.readyToGo: return # Update dynamic period self.currentPeriod = self.neckSpeed #self.targetPeriod = self.neckSpeed self.killPoints = False w = self.boardWidth / self.strings track = song.track[self.player] num = 0 enable = True renderedNotes = self.getRequiredNotesForRender(song,pos) for time, event in renderedNotes: #for time, event in track.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard): if isinstance(event, Tempo): self.tempoBpm = event.bpm continue if not isinstance(event, Note): continue if (event.noteBpm == 0.0): event.noteBpm = self.tempoBpm if self.coOpFailed: if self.coOpRestart: if time - self.coOpRescueTime < (self.currentPeriod * self.beatsPerBoard * 2): continue elif self.coOpRescueTime + (self.currentPeriod * self.beatsPerBoard * 2) < pos: self.coOpFailed = False self.coOpRestart = False Log.debug("Turning off coOpFailed. Rescue successful.") else: continue c = self.fretColors[event.number] x = (self.strings / 2 - event.number) * w z = ((time - pos) / self.currentPeriod) / self.beatsPerUnit z2 = ((time + event.length - pos) / self.currentPeriod) / self.beatsPerUnit if z > self.boardLength * .8: f = (self.boardLength - z) / (self.boardLength * .2) elif z < 0: f = min(1, max(0, 1 + z2)) else: f = 1.0 color = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1 * visibility * f) if event.length > 120: length = (event.length - 50) / self.currentPeriod / self.beatsPerUnit else: length = 0 flat = False tailOnly = False spNote = False #myfingershurt: user setting for starpower refill / replenish notes if event.star and self.spEnabled: spNote = True if event.finalStar and self.spEnabled: spNote = True if event.played or event.hopod: if event.flameCount < 1 and not self.starPowerGained: if self.gameMode2p == 6: if self.battleSuddenDeath: self.battleObjects = [1] + self.battleObjects[:2] else: self.battleObjects = [self.battleObjectsEnabled[random.randint(0,len(self.battleObjectsEnabled)-1)]] + self.battleObjects[:2] self.battleGetTime = pos self.battleObjectGained = True Log.debug("Battle Object Gained, Objects %s" % str(self.battleObjects)) else: if self.starPower < 100: self.starPower += 25 if self.starPower > 100: self.starPower = 100 self.neck.overdriveFlashCount = 0 #MFH - this triggers the oFlash strings & timer self.starPowerGained = True self.neck.ocount = 0 if event.tappable < 2: isTappable = False else: isTappable = True # Clip the played notes to the origin #myfingershurt: this should be loaded once at init, not every render... if self.notedisappear == True:#Notes keep on going when missed ###Capo### if event.played or event.hopod: tailOnly = True length += z z = 0 if length <= 0: continue if z < 0 and not (event.played or event.hopod): color = (.6, .6, .6, .5 * visibility * f) flat = True ###endCapo### else:#Notes disappear when missed if z < 0: if event.played or event.hopod: tailOnly = True length += z z = 0 if length <= 0: continue else: color = (.6, .6, .6, .5 * visibility * f) flat = True big = False self.bigMax = 0 for i in range(0,5): if self.hit[i]: big = True self.bigMax += 1 if self.spEnabled and killswitch: if event.star or event.finalStar: if big == True and tailOnly == True: self.killPoints = True color = (1,1,1,1) if z + length < -1.0: continue if event.length <= 120: length = None sustain = False if event.length > (1.4 * (60000.0 / event.noteBpm) / 4): sustain = True glPushMatrix() glTranslatef(x, (1.0 - visibility) ** (event.number + 1), z) if self.battleStatus[8]: renderNote = random.randint(0,2) else: renderNote = 0 if renderNote == 0: if big == True and num < self.bigMax: num += 1 self.renderTail(length, sustain = sustain, kill = killswitch, color = color, flat = flat, tailOnly = tailOnly, isTappable = isTappable, big = True, fret = event.number, spNote = spNote, pos = pos) else: self.renderTail(length, sustain = sustain, kill = killswitch, color = color, flat = flat, tailOnly = tailOnly, isTappable = isTappable, fret = event.number, spNote = spNote, pos = pos) glPopMatrix() if killswitch and self.killfx == 1: glBlendFunc(GL_SRC_ALPHA, GL_ONE) for time, event in self.playedNotes: step = self.currentPeriod / 16 t = time + event.length x = (self.strings / 2 - event.number) * w c = self.fretColors[event.number] s = t proj = 1.0 / self.currentPeriod / self.beatsPerUnit zStep = step * proj def waveForm(t): u = ((t - time) * -.1 + pos - time) / 64.0 + .0001 return (math.sin(event.number + self.time * -.01 + t * .03) + math.cos(event.number + self.time * .01 + t * .02)) * .1 + .1 + math.sin(u) / (5 * u) glBegin(GL_TRIANGLE_STRIP) f1 = 0 while t > time: if ((t-pos)*proj) < self.boardLength: z = (t - pos) * proj else: z = self.boardLength if z < 0: break f2 = min((s - t) / (6 * step), 1.0) a1 = waveForm(t) * f1 a2 = waveForm(t - step) * f2 if self.starPowerActive and self.theme != 2:#8bit glColor4f(self.spColor[0],self.spColor[1],self.spColor[2],1) #(.3,.7,.9,1) else: glColor4f(c[0], c[1], c[2], .5) glVertex3f(x - a1, 0, z) glVertex3f(x - a2, 0, z - zStep) glColor4f(1, 1, 1, .75) glVertex3f(x, 0, z) glVertex3f(x, 0, z - zStep) if self.starPowerActive and self.theme != 2:#8bit glColor4f(self.spColor[0],self.spColor[1],self.spColor[2],1) #(.3,.7,.9,1) else: glColor4f(c[0], c[1], c[2], .5) glVertex3f(x + a1, 0, z) glVertex3f(x + a2, 0, z - zStep) glVertex3f(x + a2, 0, z - zStep) glVertex3f(x - a2, 0, z - zStep) t -= step f1 = f2 glEnd() glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) def renderFrets(self, visibility, song, controls): w = self.boardWidth / self.strings size = (.22, .22) v = 1.0 - visibility glEnable(GL_DEPTH_TEST) #Hitglow color option - myfingershurt sez this should be a Guitar class global, not retrieved ever fret render in-game... for n in range(self.strings): f = self.fretWeight[n] c = self.fretColors[n] if f and (controls.getState(self.actions[0]) or controls.getState(self.actions[1])): f += 0.25 glColor4f(.1 + .8 * c[0] + f, .1 + .8 * c[1] + f, .1 + .8 * c[2] + f, visibility) if self.fretPress: y = v + f / 6 else: y = v / 6 x = (self.strings / 2 - n) * w if self.twoDkeys == True: if self.battleStatus[4]: fretWhamOffset = self.battleWhammyNow * .15 fretColor = (1,1,1,.5) else: fretWhamOffset = 0 fretColor = (1,1,1,1) size = (self.boardWidth/self.strings/2, self.boardWidth/self.strings/2.4) if self.battleStatus[3] and self.battleFrets != None and self.battleBreakString == n: texSize = (n/5.0+.042,n/5.0+0.158) size = (.30, .40) fretPos = 8 - round((self.battleBreakNow/self.battleBreakLimit) * 8) texY = (fretPos/8.0,(fretPos + 1.0)/8) self.engine.draw3Dtex(self.battleFrets, vertex = (size[0],size[1],-size[0],-size[1]), texcoord = (texSize[0], texY[0], texSize[1], texY[1]), coord = (x,v + .08 + fretWhamOffset,0), multiples = True,color = fretColor, depth = True) else: texSize = (n/5.0,n/5.0+0.2) texY = (0.0,1.0/3.0) if controls.getState(self.keys[n]) or controls.getState(self.keys[n+5]): texY = (1.0/3.0,2.0/3.0) if self.hit[n] or (self.battleStatus[3] and self.battleBreakString == n): texY = (2.0/3.0,1.0) self.engine.draw3Dtex(self.fretButtons, vertex = (size[0],size[1],-size[0],-size[1]), texcoord = (texSize[0], texY[0], texSize[1], texY[1]), coord = (x,v + fretWhamOffset,0), multiples = True,color = fretColor, depth = True) else: if self.keyMesh: glPushMatrix() glDepthMask(1) glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) glShadeModel(GL_SMOOTH) glRotatef(90, 0, 1, 0) glLightfv(GL_LIGHT0, GL_POSITION, (5.0, 10.0, -10.0, 0.0)) glLightfv(GL_LIGHT0, GL_AMBIENT, (.2, .2, .2, 0.0)) glLightfv(GL_LIGHT0, GL_DIFFUSE, (1.0, 1.0, 1.0, 0.0)) glRotatef(-90, 1, 0, 0) glRotatef(-90, 0, 0, 1) if n == 0: #green fret button glRotate(self.engine.theme.keyrot[0], 0, 1, 0), glTranslatef(0, 0, self.engine.theme.keypos[0]) elif n == 1: #red fret button glRotate(self.engine.theme.keyrot[1], 0, 1, 0), glTranslatef(0, 0, self.engine.theme.keypos[1]) elif n == 2: #yellow fret button glRotate(self.engine.theme.keyrot[2], 0, 1, 0), glTranslatef(0, 0, self.engine.theme.keypos[2]) elif n == 3: #blue fret button glRotate(self.engine.theme.keyrot[3], 0, 1, 0), glTranslatef(0, 0, self.engine.theme.keypos[3]) elif n == 4: #orange fret button glRotate(self.engine.theme.keyrot[4], 0, 1, 0), glTranslatef(0, 0, self.engine.theme.keypos[4]) #Mesh - Main fret #Key_001 - Top of fret (key_color) #Key_002 - Bottom of fret (key2_color) #Glow_001 - Only rendered when a note is hit along with the glow.svg #if self.complexkey == True: # glColor4f(.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], visibility) # if self.battleStatus[4]: # glTranslatef(x, y + self.battleWhammyNow * .15, 0) # else: # glTranslatef(x, y, 0) if self.keytex == True: glColor4f(1,1,1,visibility) if self.battleStatus[4]: glTranslatef(x, y + self.battleWhammyNow * .15, 0) else: glTranslatef(x, y, 0) glEnable(GL_TEXTURE_2D) getattr(self,"keytex"+chr(97+n)).texture.bind() glMatrixMode(GL_TEXTURE) glScalef(1, -1, 1) glMatrixMode(GL_MODELVIEW) glScalef(self.boardScaleX, self.boardScaleY, 1) if f and not self.hit[n]: self.keyMesh.render("Mesh_001") elif self.hit[n]: self.keyMesh.render("Mesh_002") else: self.keyMesh.render("Mesh") glMatrixMode(GL_TEXTURE) glLoadIdentity() glMatrixMode(GL_MODELVIEW) glDisable(GL_TEXTURE_2D) else: glColor4f(.1 + .8 * c[0] + f, .1 + .8 * c[1] + f, .1 + .8 * c[2] + f, visibility) if self.battleStatus[4]: glTranslatef(x, y + self.battleWhammyNow * .15 + v * 6, 0) else: glTranslatef(x, y + v * 6, 0) key = self.keyMesh if(key.find("Glow_001")) == True: key.render("Mesh") if(key.find("Key_001")) == True: glColor3f(self.keyColor[0], self.keyColor[1], self.keyColor[2]) key.render("Key_001") if(key.find("Key_002")) == True: glColor3f(self.key2Color[0], self.key2Color[1], self.key2Color[2]) key.render("Key_002") else: key.render() glDisable(GL_LIGHTING) glDisable(GL_LIGHT0) glDepthMask(0) glPopMatrix() ###################### f = self.fretActivity[n] if f and self.disableFretSFX != True: if self.glowColor[0] == -1: s = 1.0 else: s = 0.0 while s < 1: ms = s * (math.sin(self.time) * .25 + 1) if self.glowColor[0] == -2: glColor3f(c[0] * (1 - ms), c[1] * (1 - ms), c[2] * (1 - ms)) else: glColor3f(self.glowColor[0] * (1 - ms), self.glowColor[1] * (1 - ms), self.glowColor[2] * (1 - ms)) glPushMatrix() if self.battleStatus[4]: glTranslatef(x, y + self.battleWhammyNow * .15, 0) else: glTranslatef(x, y, 0) glScalef(.1 + .02 * ms * f, .1 + .02 * ms * f, .1 + .02 * ms * f) glRotatef( 90, 0, 1, 0) glRotatef(-90, 1, 0, 0) glRotatef(-90, 0, 0, 1) if self.twoDkeys == False and self.keytex == False: if(self.keyMesh.find("Glow_001")) == True: key.render("Glow_001") else: key.render() glPopMatrix() s += 0.2 #Hitglow color if self.hitglow_color == 0: glowcol = (c[0], c[1], c[2])#Same as fret elif self.hitglow_color == 1: glowcol = (1, 1, 1)#Actual color in .svg-file f += 2 if self.battleStatus[4]: self.engine.draw3Dtex(self.glowDrawing, coord = (x, y + self.battleWhammyNow * .15, 0.01), rot = (f * 90 + self.time, 0, 1, 0), texcoord = (0.0, 0.0, 1.0, 1.0), vertex = (-size[0] * f, -size[1] * f, size[0] * f, size[1] * f), multiples = True, alpha = True, color = glowcol) else: self.engine.draw3Dtex(self.glowDrawing, coord = (x, y, 0.01), rot = (f * 90 + self.time, 0, 1, 0), texcoord = (0.0, 0.0, 1.0, 1.0), vertex = (-size[0] * f, -size[1] * f, size[0] * f, size[1] * f), multiples = True, alpha = True, color = glowcol) #self.hit[n] = False #MFH -- why? This prevents frets from being rendered under / before the notes... glDisable(GL_DEPTH_TEST) def renderFreestyleFlames(self, visibility, controls): if self.flameColors[0][0][0] == -1: return w = self.boardWidth / self.strings #track = song.track[self.player] size = (.22, .22) v = 1.0 - visibility if self.disableFlameSFX != True: flameLimit = 10.0 flameLimitHalf = round(flameLimit/2.0) for fretNum in range(self.strings): if controls.getState(self.keys[fretNum]) or controls.getState(self.keys[fretNum+5]): if self.freestyleHitFlameCounts[fretNum] < flameLimit: ms = math.sin(self.time) * .25 + 1 x = (self.strings / 2 - fretNum) * w ff = 1 + 0.25 y = v + ff / 6 if self.theme == 2: y -= 0.5 #flameSize = self.flameSizes[self.scoreMultiplier - 1][fretNum] flameSize = self.flameSizes[self.cappedScoreMult - 1][fretNum] if self.theme == 0 or self.theme == 1: #THIS SETS UP GH3 COLOR, ELSE ROCKBAND(which is DEFAULT in Theme.py) flameColor = self.gh3flameColor else: #MFH - fixing crash! #try: # flameColor = self.flameColors[self.scoreMultiplier - 1][fretNum] #except IndexError: flameColor = self.fretColors[fretNum] if flameColor[0] == -2: flameColor = self.fretColors[fretNum] ff += 1.5 #ff first time is 2.75 after this if self.freestyleHitFlameCounts[fretNum] < flameLimitHalf: flamecol = tuple([flameColor[ifc] for ifc in range(3)]) rbStarColor = (.1, .1, .2, .3) xOffset = (.0, - .005, .005, .0) yOffset = (.20, .255, .255, .255) scaleMod = .6 * ms * ff scaleFix = (6.0, 5.5, 5.0, 4.7) for step in range(4): if self.starPowerActive and self.theme < 2: flamecol = self.spColor else: #Default starcolor (Rockband) flamecol = (rbStarColor[step],)*3 hfCount = self.freestyleHitFlameCounts[fretNum] if step == 0: hfCount += 1 self.engine.draw3Dtex(self.hitflames2Drawing, coord = (x+xOffset[step], y+yOffset[step], 0), rot = (90, 1, 0, 0), scale = (.25 + .05 * step + scaleMod, hfCount/scaleFix[step] + scaleMod, hfCount/scaleFix[step] + scaleMod), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) else: flameColorMod = 0.1 * (flameLimit - self.freestyleHitFlameCounts[fretNum]) flamecol = tuple([flameColor[ifc]*flameColorMod for ifc in range(3)]) xOffset = (.0, - .005, .005, .005) yOffset = (.35, .405, .355, .355) scaleMod = .6 * ms * ff scaleFix = (3.0, 2.5, 2.0, 1.7) for step in range(4): hfCount = self.freestyleHitFlameCounts[fretNum] if step == 0: hfCount += 1 else: if self.starPowerActive and self.theme < 2: flamecol = self.spColor else: #Default starcolor (Rockband) flamecol = (.4+.1*step,)*3 self.engine.draw3Dtex(self.hitflames1Drawing, coord = (x+xOffset[step], y+yOffset[step], 0), rot = (90, 1, 0, 0), scale = (.25 + .05 * step + scaleMod, hfCount/scaleFix[step] + scaleMod, hfCount/scaleFix[step] + scaleMod), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) self.freestyleHitFlameCounts[fretNum] += 1 else: #MFH - flame count is done - reset it! self.freestyleHitFlameCounts[fretNum] = 0 #MFH def renderFlames(self, visibility, song, pos, controls): if not song or self.flameColors[0][0][0] == -1: return w = self.boardWidth / self.strings track = song.track[self.player] size = (.22, .22) v = 1.0 - visibility if self.disableFlameSFX != True and (self.HCountAni == True and self.HCount2 > 12): for n in range(self.strings): f = self.fretWeight[n] c = self.fretColors[n] if f and (controls.getState(self.actions[0]) or controls.getState(self.actions[1])): f += 0.25 y = v + f / 6 x = (self.strings / 2 - n) * w f = self.fretActivity[n] if f: ms = math.sin(self.time) * .25 + 1 ff = f ff += 1.2 #myfingershurt: need to cap flameSizes use of scoreMultiplier to 4x, the 5x and 6x bass groove mults cause crash: self.cappedScoreMult = min(self.scoreMultiplier,4) flameSize = self.flameSizes[self.cappedScoreMult - 1][n] if self.theme == 0 or self.theme == 1: #THIS SETS UP GH3 COLOR, ELSE ROCKBAND(which is DEFAULT in Theme.py) flameColor = self.gh3flameColor else: flameColor = self.flameColors[self.cappedScoreMult - 1][n] flameColorMod = (1.19, 1.97, 10.59) flamecol = tuple([flameColor[ifc]*flameColorMod[ifc] for ifc in range(3)]) if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor flamecol = self.spColor else: #Default starcolor (Rockband) flamecol = (.9,.9,.9) if self.Hitanim != True: self.engine.draw3Dtex(self.hitglowDrawing, coord = (x, y + .125, 0), rot = (90, 1, 0, 0), scale = (0.5 + .6 * ms * ff, 1.5 + .6 * ms * ff, 1 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) #Alarian: Animated hitflames else: self.HCount = self.HCount + 1 if self.HCount > self.Animspeed-1: self.HCount = 0 HIndex = (self.HCount * 16 - (self.HCount * 16) % self.Animspeed) / self.Animspeed if HIndex > 15: HIndex = 0 texX = (HIndex*(1/16.0), HIndex*(1/16.0)+(1/16.0)) self.engine.draw3Dtex(self.hitglowAnim, coord = (x, y + .225, 0), rot = (90, 1, 0, 0), scale = (2.4, 1, 3.3), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (texX[0],0.0,texX[1],1.0), multiples = True, alpha = True, color = (1,1,1)) ff += .3 flameColorMod = (1.19, 1.78, 12.22) flamecol = tuple([flameColor[ifc]*flameColorMod[ifc] for ifc in range(3)]) if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor flamecol = self.spColor else: #Default starcolor (Rockband) flamecol = (.8,.8,.8) if self.Hitanim != True: self.engine.draw3Dtex(self.hitglow2Drawing, coord = (x, y + .25, .05), rot = (90, 1, 0, 0), scale = (.40 + .6 * ms * ff, 1.5 + .6 * ms * ff, 1 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) if self.disableFlameSFX != True: flameLimit = 10.0 flameLimitHalf = round(flameLimit/2.0) renderedNotes = self.getRequiredNotesForRender(song,pos) for time, event in renderedNotes: if isinstance(event, Tempo): continue if not isinstance(event, Note): continue if (event.played or event.hopod) and event.flameCount < flameLimit: ms = math.sin(self.time) * .25 + 1 x = (self.strings / 2 - event.number) * w xlightning = (self.strings / 2 - event.number)*2.2*w ff = 1 + 0.25 y = v + ff / 6 if self.theme == 2: y -= 0.5 flameSize = self.flameSizes[self.cappedScoreMult - 1][event.number] if self.theme == 0 or self.theme == 1: #THIS SETS UP GH3 COLOR, ELSE ROCKBAND(which is DEFAULT in Theme.py) flameColor = self.gh3flameColor else: flameColor = self.flameColors[self.cappedScoreMult - 1][event.number] if flameColor[0] == -2: flameColor = self.fretColors[event.number] ff += 1.5 #ff first time is 2.75 after this if self.Hitanim2 == True: self.HCount2 = self.HCount2 + 1 self.HCountAni = False if self.HCount2 > 12: if not event.length > (1.4 * (60000.0 / event.noteBpm) / 4): self.HCount2 = 0 else: self.HCountAni = True if event.flameCount < flameLimitHalf: HIndex = (self.HCount2 * 13 - (self.HCount2 * 13) % 13) / 13 if HIndex > 12 and self.HCountAni != True: HIndex = 0 texX = (HIndex*(1/13.0), HIndex*(1/13.0)+(1/13.0)) self.engine.draw3Dtex(self.hitflamesAnim, coord = (x, y + .665, 0), rot = (90, 1, 0, 0), scale = (1.6, 1.6, 4.9), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (texX[0],0.0,texX[1],1.0), multiples = True, alpha = True, color = (1,1,1)) else: flameColorMod = 0.1 * (flameLimit - event.flameCount) flamecol = tuple([ifc*flameColorMod for ifc in flameColor]) scaleChange = (3.0,2.5,2.0,1.7) yOffset = (.35, .405, .355, .355) vtx = flameSize * ff scaleMod = .6 * ms * ff for step in range(4): #draw lightning in GH themes on SP gain if step == 0 and self.theme != 2 and event.finalStar and self.spEnabled: self.engine.draw3Dtex(self.hitlightning, coord = (xlightning, y, 3.3), rot = (90, 1, 0, 0), scale = (.15 + .5 * ms * ff, event.flameCount / 3.0 + .6 * ms * ff, 2), vertex = (.4,-2,-.4,2), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = (1,1,1)) continue if step == 0: yzscaleMod = event.flameCount/ scaleChange[step] else: yzscaleMod = (event.flameCount + 1)/ scaleChange[step] if self.starPowerActive: if self.theme == 0 or self.theme == 1: spcolmod = .7+step*.1 flamecol = tuple([isp*spcolmod for isp in self.spColor]) else: flamecol = (.4+step*.1,)*3#Default starcolor (Rockband) if self.hitFlamesPresent == True: self.engine.draw3Dtex(self.hitflames1Drawing, coord = (x - .005, y + yOffset[step], 0), rot = (90, 1, 0, 0), scale = (.25 + step*.05 + scaleMod, yzscaleMod + scaleMod, yzscaleMod + scaleMod), vertex = (-vtx,-vtx,vtx,vtx), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) elif self.hitFlamesPresent == True and self.Hitanim2 == False: self.HCount2 = 13 self.HCountAni = True if event.flameCount < flameLimitHalf: flamecol = flameColor if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor spcolmod = .3 flamecol = tuple([isp*spcolmod for isp in self.spColor]) else: #Default starcolor (Rockband) flamecol = (.1,.1,.1) self.engine.draw3Dtex(self.hitflames2Drawing, coord = (x, y + .20, 0), rot = (90, 1, 0, 0), scale = (.25 + .6 * ms * ff, event.flameCount/6.0 + .6 * ms * ff, event.flameCount / 6.0 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) for i in range(3): if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor spcolmod = 0.4+i*0.1 flamecol = tuple([isp*spcolmod for isp in self.spColor]) else: #Default starcolor (Rockband) flamecol = (0.1+i*0.1,)*3 self.engine.draw3Dtex(self.hitflames2Drawing, coord = (x-.005, y + .255, 0), rot = (90, 1, 0, 0), scale = (.30 + i*0.05 + .6 * ms * ff, event.flameCount/(5.5 - i*0.4) + .6 * ms * ff, event.flameCount / (5.5 - i*0.4) + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) else: flameColorMod = 0.1 * (flameLimit - event.flameCount) flamecol = tuple([ifc*flameColorMod for ifc in flameColor]) scaleChange = (3.0,2.5,2.0,1.7) yOffset = (.35, .405, .355, .355) vtx = flameSize * ff scaleMod = .6 * ms * ff for step in range(4): #draw lightning in GH themes on SP gain if step == 0 and self.theme != 2 and event.finalStar and self.spEnabled: self.engine.draw3Dtex(self.hitlightning, coord = (xlightning, y, 3.3), rot = (90, 1, 0, 0), scale = (.15 + .5 * ms * ff, event.flameCount / 3.0 + .6 * ms * ff, 2), vertex = (.4,-2,-.4,2), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = (1,1,1)) continue if step == 0: yzscaleMod = event.flameCount/ scaleChange[step] else: yzscaleMod = (event.flameCount + 1)/ scaleChange[step] if self.starPowerActive: if self.theme == 0 or self.theme == 1: spcolmod = .7+step*.1 flamecol = tuple([isp*spcolmod for isp in self.spColor]) else: flamecol = (.4+step*.1,)*3#Default starcolor (Rockband) self.engine.draw3Dtex(self.hitflames1Drawing, coord = (x - .005, y + yOffset[step], 0), rot = (90, 1, 0, 0), scale = (.25 + step*.05 + scaleMod, yzscaleMod + scaleMod, yzscaleMod + scaleMod), vertex = (-vtx,-vtx,vtx,vtx), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) event.flameCount += 1 def render(self, visibility, song, pos, controls, killswitch): if shaders.turnon: shaders.globals["dfActive"] = self.drumFillsActive shaders.globals["breActive"] = self.freestyleActive shaders.globals["rockLevel"] = self.rockLevel if shaders.globals["killswitch"] != killswitch: shaders.globals["killswitchPos"] = pos shaders.globals["killswitch"] = killswitch shaders.modVar("height",0.2,0.2,1.0,"tail") if not self.starNotesSet == True: self.totalNotes = 0 for time, event in song.track[self.player].getAllEvents(): if not isinstance(event, Note): continue self.totalNotes += 1 stars = [] maxStars = [] maxPhrase = self.totalNotes/120 for q in range(0,maxPhrase): for n in range(0,10): stars.append(self.totalNotes/maxPhrase*(q)+n+maxPhrase/4) maxStars.append(self.totalNotes/maxPhrase*(q)+10+maxPhrase/4) i = 0 for time, event in song.track[self.player].getAllEvents(): if not isinstance(event, Note): continue for a in stars: if i == a: self.starNotes.append(time) event.star = True for a in maxStars: if i == a: self.maxStars.append(time) event.finalStar = True i += 1 for time, event in song.track[self.player].getAllEvents(): if not isinstance(event, Note): continue for q in self.starNotes: if time == q: event.star = True for q in self.maxStars: #if time == q and not event.finalStar: # event.star = True if time == q: #MFH - no need to mark only the final SP phrase note as the finalStar as in drums, they will be hit simultaneously here. event.finalStar = True self.starNotesSet = True if not (self.coOpFailed and not self.coOpRestart): glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_COLOR_MATERIAL) if self.leftyMode: if not self.battleStatus[6]: glScalef(-1, 1, 1) elif self.battleStatus[6]: glScalef(-1, 1, 1) if self.freestyleActive: self.renderTails(visibility, song, pos, killswitch) self.renderNotes(visibility, song, pos, killswitch) self.renderFreestyleLanes(visibility, song, pos) #MFH - render the lanes on top of the notes. self.renderFrets(visibility, song, controls) if self.hitFlamesPresent: #MFH - only if present! self.renderFreestyleFlames(visibility, controls) #MFH - freestyle hit flames else: self.renderTails(visibility, song, pos, killswitch) if self.fretsUnderNotes: #MFH if self.twoDnote == True: self.renderFrets(visibility, song, controls) self.renderNotes(visibility, song, pos, killswitch) else: self.renderNotes(visibility, song, pos, killswitch) self.renderFrets(visibility, song, controls) else: self.renderNotes(visibility, song, pos, killswitch) self.renderFrets(visibility, song, controls) self.renderFreestyleLanes(visibility, song, pos) #MFH - render the lanes on top of the notes. if self.hitFlamesPresent: #MFH - only if present! self.renderFlames(visibility, song, pos, controls) #MFH - only when freestyle inactive! if self.leftyMode: if not self.battleStatus[6]: glScalef(-1, 1, 1) elif self.battleStatus[6]: glScalef(-1, 1, 1) #return notes #MFH - corrected and optimized: #def getRequiredNotesMFH(self, song, pos): def getRequiredNotesMFH(self, song, pos, hopoTroubleCheck = False): if self.battleStatus[2] and self.difficulty != 0: if pos < self.battleStartTimes[2] + self.currentPeriod * self.beatsPerBoard or pos > self.battleStartTimes[2] - self.currentPeriod * self.beatsPerBoard + self.battleDiffUpLength: song.difficulty[self.player] = Song.difficulties[self.battleDiffUpValue] else: song.difficulty[self.player] = Song.difficulties[self.battleDiffUpValue - 1] track = song.track[self.player] if hopoTroubleCheck: notes = [(time, event) for time, event in track.getEvents(pos, pos + (self.earlyMargin*2)) if isinstance(event, Note)] notes = [(time, event) for time, event in notes if not time==pos] #MFH - filter out the problem note that caused this check! else: notes = [(time, event) for time, event in track.getEvents(pos - self.lateMargin, pos + self.earlyMargin) if isinstance(event, Note)] notes = [(time, event) for time, event in notes if not (event.hopod or event.played or event.skipped)] notes = [(time, event) for time, event in notes if (time >= (pos - self.lateMargin)) and (time <= (pos + self.earlyMargin))] sorted(notes, key=lambda x: x[0]) if self.battleStatus[7]: notes = self.getDoubleNotes(notes) return sorted(notes, key=lambda x: x[0]) #MFH - what the hell, this should be sorted by TIME not note number.... def getDoubleNotes(self, notes): if self.battleStatus[7] and notes != []: notes = sorted(notes, key=lambda x: x[0]) curTime = 0 tempnotes = [] tempnumbers = [] tempnote = None curNumbers = [] noteCount = 0 for time, note in notes: noteCount += 1 if not isinstance(note, Note): if noteCount == len(notes) and len(curNumbers) < 3 and len(curNumbers) > 0: maxNote = curNumbers[0] minNote = curNumbers[0] for i in range(0, len(curNumbers)): if curNumbers[i] > maxNote: maxNote = curNumbers[i] if curNumbers[i] < minNote: minNote = curNumbers[i] curNumbers = [] if maxNote < 4: tempnumbers.append(maxNote + 1) elif minNote > 0: tempnumbers.append(minNote - 1) else: tempnumbers.append(2) elif noteCount == len(notes) and len(curNumbers) > 2: tempnumbers.append(-1) curNumbers = [] continue if time != curTime: if curTime != 0 and len(curNumbers) < 3: maxNote = curNumbers[0] minNote = curNumbers[0] for i in range(0, len(curNumbers)): if curNumbers[i] > maxNote: maxNote = curNumbers[i] if curNumbers[i] < minNote: minNote = curNumbers[i] curNumbers = [] if maxNote < 4: tempnumbers.append(maxNote + 1) elif minNote > 0: tempnumbers.append(minNote - 1) else: tempnumbers.append(2) elif (curTime != 0 or noteCount == len(notes)) and len(curNumbers) > 2: tempnumbers.append(-1) curNumbers = [] tempnotes.append((time,deepcopy(note))) curTime = time curNumbers.append(note.number) if noteCount == len(notes) and len(curNumbers) < 3: maxNote = curNumbers[0] minNote = curNumbers[0] for i in range(0, len(curNumbers)): if curNumbers[i] > maxNote: maxNote = curNumbers[i] if curNumbers[i] < minNote: minNote = curNumbers[i] curNumbers = [] if maxNote < 4: tempnumbers.append(maxNote + 1) elif minNote > 0: tempnumbers.append(minNote - 1) else: tempnumbers.append(2) elif noteCount == len(notes) and len(curNumbers) > 2: tempnumbers.append(-1) curNumbers = [] else: curNumbers.append(note.number) if noteCount == len(notes) and len(curNumbers) < 3: maxNote = curNumbers[0] minNote = curNumbers[0] for i in range(0, len(curNumbers)): if curNumbers[i] > maxNote: maxNote = curNumbers[i] if curNumbers[i] < minNote: minNote = curNumbers[i] curNumbers = [] if maxNote < 4: tempnumbers.append(maxNote + 1) elif minNote > 0: tempnumbers.append(minNote - 1) else: tempnumbers.append(2) elif noteCount == len(notes) and len(curNumbers) > 2: tempnumbers.append(-1) curNumbers = [] noteCount = 0 for time, note in tempnotes: if tempnumbers[noteCount] != -1: note.number = tempnumbers[noteCount] noteCount += 1 if time > self.battleStartTimes[7] + self.currentPeriod * self.beatsPerBoard and time < self.battleStartTimes[7] - self.currentPeriod * self.beatsPerBoard + self.battleDoubleLength: notes.append((time,note)) else: noteCount += 1 return sorted(notes, key=lambda x: x[0]) def getRequiredNotesForRender(self, song, pos): if self.battleStatus[2] and self.difficulty != 0: Log.debug(self.battleDiffUpValue) song.difficulty[self.player] = Song.difficulties[self.battleDiffUpValue] track0 = song.track[self.player] notes0 = [(time, event) for time, event in track0.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard)] song.difficulty[self.player] = Song.difficulties[self.battleDiffUpValue - 1] track1 = song.track[self.player] notes1 = [(time, event) for time, event in track1.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard)] notes = [] for time,note in notes0: if time < self.battleStartTimes[2] + self.currentPeriod * self.beatsPerBoard or time > self.battleStartTimes[2] - self.currentPeriod * self.beatsPerBoard + self.battleDiffUpLength: notes.append((time,note)) for time,note in notes1: if time > self.battleStartTimes[2] + self.currentPeriod * self.beatsPerBoard and time < self.battleStartTimes[2] - self.currentPeriod * self.beatsPerBoard + self.battleDiffUpLength: notes.append((time,note)) notes0 = None notes1 = None track0 = None track1 = None notes = sorted(notes, key=lambda x: x[0]) #Log.debug(notes) else: track = song.track[self.player] notes = [(time, event) for time, event in track.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard)] if self.battleStatus[7]: notes = self.getDoubleNotes(notes) return notes #MFH - corrected and optimized: def getRequiredNotesForJurgenOnTime(self, song, pos): track = song.track[self.player] notes = [(time, event) for time, event in track.getEvents(pos - self.lateMargin, pos + 30) if isinstance(event, Note)] notes = [(time, event) for time, event in notes if not (event.hopod or event.played or event.skipped)] if self.battleStatus[7]: notes = self.getDoubleNotes(notes) return sorted(notes, key=lambda x: x[0]) #MFH - what the hell, this should be sorted by TIME not note number.... def controlsMatchNotes(self, controls, notes): # no notes? if not notes: return False # check each valid chord chords = {} for time, note in notes: if not time in chords: chords[time] = [] chords[time].append((time, note)) #Make sure the notes are in the right time order chordlist = chords.values() chordlist.sort(lambda a, b: cmp(a[0][0], b[0][0])) twochord = 0 for chord in chordlist: # matching keys? requiredKeys = [note.number for time, note in chord] requiredKeys = self.uniqify(requiredKeys) if len(requiredKeys) > 2 and self.twoChordMax == True: twochord = 0 for k in self.keys: if controls.getState(k): twochord += 1 if twochord == 2: skipped = len(requiredKeys) - 2 requiredKeys = [min(requiredKeys), max(requiredKeys)] else: twochord = 0 for n in range(self.strings): if n in requiredKeys and not (controls.getState(self.keys[n]) or controls.getState(self.keys[n+5])): return False if not n in requiredKeys and (controls.getState(self.keys[n]) or controls.getState(self.keys[n+5])): # The lower frets can be held down if n > max(requiredKeys): return False if twochord != 0: if twochord != 2: for time, note in chord: note.played = True else: self.twoChordApply = True for time, note in chord: note.skipped = True chord[0][1].skipped = False chord[-1][1].skipped = False chord[0][1].played = True chord[-1][1].played = True if twochord == 2: self.twoChord += skipped return True def controlsMatchNotes2(self, controls, notes, hopo = False): # no notes? if not notes: return False # check each valid chord chords = {} for time, note in notes: if note.hopod == True and (controls.getState(self.keys[note.number]) or controls.getState(self.keys[note.number + 5])): #if hopo == True and controls.getState(self.keys[note.number]): self.playedNotes = [] return True if not time in chords: chords[time] = [] chords[time].append((time, note)) #Make sure the notes are in the right time order chordlist = chords.values() chordlist.sort(lambda a, b: cmp(a[0][0], b[0][0])) twochord = 0 for chord in chordlist: # matching keys? requiredKeys = [note.number for time, note in chord] requiredKeys = self.uniqify(requiredKeys) if len(requiredKeys) > 2 and self.twoChordMax == True: twochord = 0 for n, k in enumerate(self.keys): if controls.getState(k): twochord += 1 if twochord == 2: skipped = len(requiredKeys) - 2 requiredKeys = [min(requiredKeys), max(requiredKeys)] else: twochord = 0 for n in range(self.strings): if n in requiredKeys and not (controls.getState(self.keys[n]) or controls.getState(self.keys[n+5])): return False if not n in requiredKeys and (controls.getState(self.keys[n]) or controls.getState(self.keys[n+5])): # The lower frets can be held down if hopo == False and n >= min(requiredKeys): return False if twochord != 0: if twochord != 2: for time, note in chord: note.played = True else: self.twoChordApply = True for time, note in chord: note.skipped = True chord[0][1].skipped = False chord[-1][1].skipped = False chord[0][1].played = True chord[-1][1].played = True if twochord == 2: self.twoChord += skipped return True def controlsMatchNotes3(self, controls, notes, hopo = False): # no notes? if not notes: return False # check each valid chord chords = {} for time, note in notes: if note.hopod == True and (controls.getState(self.keys[note.number]) or controls.getState(self.keys[note.number + 5])): #if hopo == True and controls.getState(self.keys[note.number]): self.playedNotes = [] return True if not time in chords: chords[time] = [] chords[time].append((time, note)) #Make sure the notes are in the right time order chordlist = chords.values() #chordlist.sort(lambda a, b: cmp(a[0][0], b[0][0])) chordlist.sort(key=lambda a: a[0][0]) self.missedNotes = [] self.missedNoteNums = [] twochord = 0 for chord in chordlist: # matching keys? requiredKeys = [note.number for time, note in chord] requiredKeys = self.uniqify(requiredKeys) if len(requiredKeys) > 2 and self.twoChordMax == True: twochord = 0 for n, k in enumerate(self.keys): if controls.getState(k): twochord += 1 if twochord == 2: skipped = len(requiredKeys) - 2 requiredKeys = [min(requiredKeys), max(requiredKeys)] else: twochord = 0 if (self.controlsMatchNote3(controls, chord, requiredKeys, hopo)): if twochord != 2: for time, note in chord: note.played = True else: self.twoChordApply = True for time, note in chord: note.skipped = True chord[0][1].skipped = False chord[-1][1].skipped = False chord[0][1].played = True chord[-1][1].played = True break if hopo == True: break self.missedNotes.append(chord) else: self.missedNotes = [] self.missedNoteNums = [] for chord in self.missedNotes: for time, note in chord: if self.debugMode: self.missedNoteNums.append(note.number) note.skipped = True note.played = False if twochord == 2: self.twoChord += skipped return True #MFH - special function for HOPO intentions checking def controlsMatchNextChord(self, controls, notes): # no notes? if not notes: return False # check each valid chord chords = {} for time, note in notes: if not time in chords: chords[time] = [] chords[time].append((time, note)) #Make sure the notes are in the right time order chordlist = chords.values() chordlist.sort(key=lambda a: a[0][0]) twochord = 0 for chord in chordlist: # matching keys? self.requiredKeys = [note.number for time, note in chord] self.requiredKeys = self.uniqify(self.requiredKeys) if len(self.requiredKeys) > 2 and self.twoChordMax == True: twochord = 0 self.twoChordApply = True for n, k in enumerate(self.keys): if controls.getState(k): twochord += 1 if twochord == 2: skipped = len(self.requiredKeys) - 2 self.requiredKeys = [min(self.requiredKeys), max(self.requiredKeys)] else: twochord = 0 if (self.controlsMatchNote3(controls, chord, self.requiredKeys, False)): return True else: return False def uniqify(self, seq, idfun=None): # order preserving if idfun is None: def idfun(x): return x seen = {} result = [] for item in seq: marker = idfun(item) # in old Python versions: # if seen.has_key(marker) # but in new ones: if marker in seen: continue seen[marker] = 1 result.append(item) return result def controlsMatchNote3(self, controls, chordTuple, requiredKeys, hopo): if len(chordTuple) > 1: #Chords must match exactly for n in range(self.strings): if (n in requiredKeys and not (controls.getState(self.keys[n]) or controls.getState(self.keys[n+5]))) or (n not in requiredKeys and (controls.getState(self.keys[n]) or controls.getState(self.keys[n+5]))): return False else: #Single Note must match that note requiredKey = requiredKeys[0] if not controls.getState(self.keys[requiredKey]) and not controls.getState(self.keys[requiredKey+5]): return False #myfingershurt: this is where to filter out higher frets held when HOPOing: if hopo == False or self.hopoStyle == 2 or self.hopoStyle == 3: #Check for higher numbered frets if not a HOPO or if GH2 strict mode for n, k in enumerate(self.keys): if (n > requiredKey and n < 5) or (n > 4 and n > requiredKey + 5): #higher numbered frets cannot be held if controls.getState(k): return False return True def areNotesTappable(self, notes): if not notes: return for time, note in notes: if note.tappable > 1: return True return False def startPick(self, song, pos, controls, hopo = False): if hopo == True: res = startPick2(song, pos, controls, hopo) return res if not song: return False if not song.readyToGo: return False self.playedNotes = [] self.matchingNotes = self.getRequiredNotes(song, pos) if self.controlsMatchNotes(controls, self.matchingNotes): self.pickStartPos = pos for time, note in self.matchingNotes: if note.skipped == True: continue self.pickStartPos = max(self.pickStartPos, time) note.played = True self.playedNotes.append([time, note]) if self.guitarSolo: self.currentGuitarSoloHitNotes += 1 return True return False def startPick2(self, song, pos, controls, hopo = False): if not song: return False if not song.readyToGo: return False self.playedNotes = [] self.matchingNotes = self.getRequiredNotes2(song, pos, hopo) if self.controlsMatchNotes2(controls, self.matchingNotes, hopo): self.pickStartPos = pos for time, note in self.matchingNotes: if note.skipped == True: continue self.pickStartPos = max(self.pickStartPos, time) if hopo: note.hopod = True else: note.played = True if note.tappable == 1 or note.tappable == 2: self.hopoActive = time self.wasLastNoteHopod = True elif note.tappable == 3: self.hopoActive = -time self.wasLastNoteHopod = True else: self.hopoActive = 0 self.wasLastNoteHopod = False self.playedNotes.append([time, note]) if self.guitarSolo: self.currentGuitarSoloHitNotes += 1 self.hopoLast = note.number return True return False def startPick3(self, song, pos, controls, hopo = False): if not song: return False if not song.readyToGo: return False self.lastPlayedNotes = self.playedNotes self.playedNotes = [] self.matchingNotes = self.getRequiredNotesMFH(song, pos) self.controlsMatchNotes3(controls, self.matchingNotes, hopo) #myfingershurt for time, note in self.matchingNotes: if note.played != True: continue if shaders.turnon: shaders.var["fret"][self.player][note.number]=shaders.time() shaders.var["fretpos"][self.player][note.number]=pos self.pickStartPos = pos self.pickStartPos = max(self.pickStartPos, time) if hopo: note.hopod = True else: note.played = True #self.wasLastNoteHopod = False if note.tappable == 1 or note.tappable == 2: self.hopoActive = time self.wasLastNoteHopod = True elif note.tappable == 3: self.hopoActive = -time self.wasLastNoteHopod = True if hopo: #MFH - you just tapped a 3 - make a note of it. (har har) self.hopoProblemNoteNum = note.number self.sameNoteHopoString = True else: self.hopoActive = 0 self.wasLastNoteHopod = False self.hopoLast = note.number self.playedNotes.append([time, note]) if self.guitarSolo: self.currentGuitarSoloHitNotes += 1 #myfingershurt: be sure to catch when a chord is played if len(self.playedNotes) > 1: lastPlayedNote = None for time, note in self.playedNotes: if isinstance(lastPlayedNote, Note): if note.tappable == 1 and lastPlayedNote.tappable == 1: self.LastStrumWasChord = True #self.sameNoteHopoString = False else: self.LastStrumWasChord = False lastPlayedNote = note elif len(self.playedNotes) > 0: #ensure at least that a note was played here self.LastStrumWasChord = False if len(self.playedNotes) != 0: return True return False def soloFreestylePick(self, song, pos, controls): numHits = 0 for theFret in range(5): self.freestyleHit[theFret] = controls.getState(self.keys[theFret+5]) if self.freestyleHit[theFret]: if shaders.turnon: shaders.var["fret"][self.player][theFret]=shaders.time() shaders.var["fretpos"][self.player][theFret]=pos numHits += 1 return numHits #MFH - TODO - handle freestyle picks here def freestylePick(self, song, pos, controls): numHits = 0 #if not song: # return numHits if not controls.getState(self.actions[0]) and not controls.getState(self.actions[1]): return 0 for theFret in range(5): self.freestyleHit[theFret] = controls.getState(self.keys[theFret]) if self.freestyleHit[theFret]: if shaders.turnon: shaders.var["fret"][self.player][theFret]=shaders.time() shaders.var["fretpos"][self.player][theFret]=pos numHits += 1 return numHits def endPick(self, pos): for time, note in self.playedNotes: if time + note.length > pos + self.noteReleaseMargin: self.playedNotes = [] return False self.playedNotes = [] return True def getPickLength(self, pos): if not self.playedNotes: return 0.0 # The pick length is limited by the played notes pickLength = pos - self.pickStartPos for time, note in self.playedNotes: pickLength = min(pickLength, note.length) return pickLength def coOpRescue(self, pos): self.coOpRestart = True #initializes Restart Timer self.coOpRescueTime = pos self.starPower = 0 Log.debug("Rescued at " + str(pos)) def run(self, ticks, pos, controls): if not self.paused: self.time += ticks #MFH - Determine which frame to display for starpower notes if self.starspin: self.indexCount = self.indexCount + 1 if self.indexCount > self.Animspeed-1: self.indexCount = 0 self.starSpinFrameIndex = (self.indexCount * self.starSpinFrames - (self.indexCount * self.starSpinFrames) % self.Animspeed) / self.Animspeed if self.starSpinFrameIndex > self.starSpinFrames - 1: self.starSpinFrameIndex = 0 #myfingershurt: must not decrease SP if paused. if self.starPowerActive == True and self.paused == False: self.starPower -= ticks/self.starPowerDecreaseDivisor if self.starPower <= 0: self.starPower = 0 self.starPowerActive = False #MFH - call to play star power deactivation sound, if it exists (if not play nothing) if self.engine.data.starDeActivateSoundFound: #self.engine.data.starDeActivateSound.setVolume(self.sfxVolume) self.engine.data.starDeActivateSound.play() # update frets if self.editorMode: if (controls.getState(self.actions[0]) or controls.getState(self.actions[1])): for i in range(self.strings): if controls.getState(self.keys[i]) or controls.getState(self.keys[i+5]): activeFrets.append(i) activeFrets = activeFrets or [self.selectedString] else: activeFrets = [] else: activeFrets = [note.number for time, note in self.playedNotes] for n in range(self.strings): if controls.getState(self.keys[n]) or controls.getState(self.keys[n+5]) or (self.editorMode and self.selectedString == n): self.fretWeight[n] = 0.5 else: self.fretWeight[n] = max(self.fretWeight[n] - ticks / 64.0, 0.0) if n in activeFrets: self.fretActivity[n] = min(self.fretActivity[n] + ticks / 32.0, 1.0) else: self.fretActivity[n] = max(self.fretActivity[n] - ticks / 64.0, 0.0) #MFH - THIS is where note sustains should be determined... NOT in renderNotes / renderFrets / renderFlames -.- if self.fretActivity[n]: self.hit[n] = True else: self.hit[n] = False if self.vbpmLogicType == 0: #MFH - VBPM (old) if self.currentBpm != self.targetBpm: diff = self.targetBpm - self.currentBpm if (round((diff * .03), 4) != 0): self.currentBpm = round(self.currentBpm + (diff * .03), 4) else: self.currentBpm = self.targetBpm self.setBPM(self.currentBpm) # glorandwarf: was setDynamicBPM(self.currentBpm) for time, note in self.playedNotes: if pos > time + note.length: return False return True
cherbib/fofix
src/Guitar.py
Python
gpl-2.0
95,964
# Copyright 1999 by Jeffrey Chang. All rights reserved. # Copyright 2000 by Jeffrey Chang. All rights reserved. # Revisions Copyright 2007 by Peter Cock. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """Module for working with Prosite files from ExPASy (DEPRECATED). Most of the functionality in this module has moved to Bio.ExPASy.Prosite; please see Bio.ExPASy.Prosite.read To read a Prosite file containing one entry. Bio.ExPASy.Prosite.parse Iterates over entries in a Prosite file. Bio.ExPASy.Prosite.Record Holds Prosite data. For scan_sequence_expasy Scan a sequence for occurrences of Prosite patterns. _extract_pattern_hits Extract Prosite patterns from a web page. PatternHit Holds data from a hit against a Prosite pattern. please see the new module Bio.ExPASy.ScanProsite. The other functions and classes in Bio.Prosite (including Bio.Prosite.index_file and Bio.Prosite.Dictionary) are considered deprecated, and were not moved to Bio.ExPASy.Prosite. If you use this functionality, please contact the Biopython developers at biopython-dev@biopython.org to avoid permanent removal of this module from Biopython. This module provides code to work with the prosite dat file from Prosite. http://www.expasy.ch/prosite/ Tested with: Release 15.0, July 1998 Release 16.0, July 1999 Release 17.0, Dec 2001 Release 19.0, Mar 2006 Functions: parse Iterates over entries in a Prosite file. scan_sequence_expasy Scan a sequence for occurrences of Prosite patterns. index_file Index a Prosite file for a Dictionary. _extract_record Extract Prosite data from a web page. _extract_pattern_hits Extract Prosite patterns from a web page. Classes: Record Holds Prosite data. PatternHit Holds data from a hit against a Prosite pattern. Dictionary Accesses a Prosite file using a dictionary interface. RecordParser Parses a Prosite record into a Record object. _Scanner Scans Prosite-formatted data. _RecordConsumer Consumes Prosite data to a Record object. """ import warnings import Bio warnings.warn("Bio.Prosite is deprecated, and will be removed in a"\ " future release of Biopython. Most of the functionality " " is now provided by Bio.ExPASy.Prosite. If you want to " " continue to use Bio.Prosite, please get in contact " " via the mailing lists to avoid its permanent removal from"\ " Biopython.", Bio.BiopythonDeprecationWarning) from types import * import re import sgmllib from Bio import File from Bio import Index from Bio.ParserSupport import * # There is probably a cleaner way to write the read/parse functions # if we don't use the "parser = RecordParser(); parser.parse(handle)" # approach. Leaving that for the next revision of Bio.Prosite. def parse(handle): import cStringIO parser = RecordParser() text = "" for line in handle: text += line if line[:2]=='//': handle = cStringIO.StringIO(text) record = parser.parse(handle) text = "" if not record: # Then this was the copyright notice continue yield record def read(handle): parser = RecordParser() try: record = parser.parse(handle) except ValueError, error: if error.message=="There doesn't appear to be a record": raise ValueError("No Prosite record found") else: raise error # We should have reached the end of the record by now remainder = handle.read() if remainder: raise ValueError("More than one Prosite record found") return record class Record: """Holds information from a Prosite record. Members: name ID of the record. e.g. ADH_ZINC type Type of entry. e.g. PATTERN, MATRIX, or RULE accession e.g. PS00387 created Date the entry was created. (MMM-YYYY) data_update Date the 'primary' data was last updated. info_update Date data other than 'primary' data was last updated. pdoc ID of the PROSITE DOCumentation. description Free-format description. pattern The PROSITE pattern. See docs. matrix List of strings that describes a matrix entry. rules List of rule definitions (from RU lines). (strings) prorules List of prorules (from PR lines). (strings) NUMERICAL RESULTS nr_sp_release SwissProt release. nr_sp_seqs Number of seqs in that release of Swiss-Prot. (int) nr_total Number of hits in Swiss-Prot. tuple of (hits, seqs) nr_positive True positives. tuple of (hits, seqs) nr_unknown Could be positives. tuple of (hits, seqs) nr_false_pos False positives. tuple of (hits, seqs) nr_false_neg False negatives. (int) nr_partial False negatives, because they are fragments. (int) COMMENTS cc_taxo_range Taxonomic range. See docs for format cc_max_repeat Maximum number of repetitions in a protein cc_site Interesting site. list of tuples (pattern pos, desc.) cc_skip_flag Can this entry be ignored? cc_matrix_type cc_scaling_db cc_author cc_ft_key cc_ft_desc cc_version version number (introduced in release 19.0) DATA BANK REFERENCES - The following are all lists of tuples (swiss-prot accession, swiss-prot name) dr_positive dr_false_neg dr_false_pos dr_potential Potential hits, but fingerprint region not yet available. dr_unknown Could possibly belong pdb_structs List of PDB entries. """ def __init__(self): self.name = '' self.type = '' self.accession = '' self.created = '' self.data_update = '' self.info_update = '' self.pdoc = '' self.description = '' self.pattern = '' self.matrix = [] self.rules = [] self.prorules = [] self.postprocessing = [] self.nr_sp_release = '' self.nr_sp_seqs = '' self.nr_total = (None, None) self.nr_positive = (None, None) self.nr_unknown = (None, None) self.nr_false_pos = (None, None) self.nr_false_neg = None self.nr_partial = None self.cc_taxo_range = '' self.cc_max_repeat = '' self.cc_site = [] self.cc_skip_flag = '' self.dr_positive = [] self.dr_false_neg = [] self.dr_false_pos = [] self.dr_potential = [] self.dr_unknown = [] self.pdb_structs = [] class PatternHit: """Holds information from a hit against a Prosite pattern. Members: name ID of the record. e.g. ADH_ZINC accession e.g. PS00387 pdoc ID of the PROSITE DOCumentation. description Free-format description. matches List of tuples (start, end, sequence) where start and end are indexes of the match, and sequence is the sequence matched. """ def __init__(self): self.name = None self.accession = None self.pdoc = None self.description = None self.matches = [] def __str__(self): lines = [] lines.append("%s %s %s" % (self.accession, self.pdoc, self.name)) lines.append(self.description) lines.append('') if len(self.matches) > 1: lines.append("Number of matches: %s" % len(self.matches)) for i in range(len(self.matches)): start, end, seq = self.matches[i] range_str = "%d-%d" % (start, end) if len(self.matches) > 1: lines.append("%7d %10s %s" % (i+1, range_str, seq)) else: lines.append("%7s %10s %s" % (' ', range_str, seq)) return "\n".join(lines) class Dictionary: """Accesses a Prosite file using a dictionary interface. """ __filename_key = '__filename' def __init__(self, indexname, parser=None): """__init__(self, indexname, parser=None) Open a Prosite Dictionary. indexname is the name of the index for the dictionary. The index should have been created using the index_file function. parser is an optional Parser object to change the results into another form. If set to None, then the raw contents of the file will be returned. """ self._index = Index.Index(indexname) self._handle = open(self._index[Dictionary.__filename_key]) self._parser = parser def __len__(self): return len(self._index) def __getitem__(self, key): start, len = self._index[key] self._handle.seek(start) data = self._handle.read(len) if self._parser is not None: return self._parser.parse(File.StringHandle(data)) return data def __getattr__(self, name): return getattr(self._index, name) class RecordParser(AbstractParser): """Parses Prosite data into a Record object. """ def __init__(self): self._scanner = _Scanner() self._consumer = _RecordConsumer() def parse(self, handle): self._scanner.feed(handle, self._consumer) return self._consumer.data class _Scanner: """Scans Prosite-formatted data. Tested with: Release 15.0, July 1998 """ def feed(self, handle, consumer): """feed(self, handle, consumer) Feed in Prosite data for scanning. handle is a file-like object that contains prosite data. consumer is a Consumer object that will receive events as the report is scanned. """ if isinstance(handle, File.UndoHandle): uhandle = handle else: uhandle = File.UndoHandle(handle) consumer.finished = False while not consumer.finished: line = uhandle.peekline() if not line: break elif is_blank_line(line): # Skip blank lines between records uhandle.readline() continue elif line[:2] == 'ID': self._scan_record(uhandle, consumer) elif line[:2] == 'CC': self._scan_copyrights(uhandle, consumer) else: raise ValueError("There doesn't appear to be a record") def _scan_copyrights(self, uhandle, consumer): consumer.start_copyrights() self._scan_line('CC', uhandle, consumer.copyright, any_number=1) self._scan_terminator(uhandle, consumer) consumer.end_copyrights() def _scan_record(self, uhandle, consumer): consumer.start_record() for fn in self._scan_fns: fn(self, uhandle, consumer) # In Release 15.0, C_TYPE_LECTIN_1 has the DO line before # the 3D lines, instead of the other way around. # Thus, I'll give the 3D lines another chance after the DO lines # are finished. if fn is self._scan_do.im_func: self._scan_3d(uhandle, consumer) consumer.end_record() def _scan_line(self, line_type, uhandle, event_fn, exactly_one=None, one_or_more=None, any_number=None, up_to_one=None): # Callers must set exactly one of exactly_one, one_or_more, or # any_number to a true value. I do not explicitly check to # make sure this function is called correctly. # This does not guarantee any parameter safety, but I # like the readability. The other strategy I tried was have # parameters min_lines, max_lines. if exactly_one or one_or_more: read_and_call(uhandle, event_fn, start=line_type) if one_or_more or any_number: while 1: if not attempt_read_and_call(uhandle, event_fn, start=line_type): break if up_to_one: attempt_read_and_call(uhandle, event_fn, start=line_type) def _scan_id(self, uhandle, consumer): self._scan_line('ID', uhandle, consumer.identification, exactly_one=1) def _scan_ac(self, uhandle, consumer): self._scan_line('AC', uhandle, consumer.accession, exactly_one=1) def _scan_dt(self, uhandle, consumer): self._scan_line('DT', uhandle, consumer.date, exactly_one=1) def _scan_de(self, uhandle, consumer): self._scan_line('DE', uhandle, consumer.description, exactly_one=1) def _scan_pa(self, uhandle, consumer): self._scan_line('PA', uhandle, consumer.pattern, any_number=1) def _scan_ma(self, uhandle, consumer): self._scan_line('MA', uhandle, consumer.matrix, any_number=1) ## # ZN2_CY6_FUNGAL_2, DNAJ_2 in Release 15 ## # contain a CC line buried within an 'MA' line. Need to check ## # for that. ## while 1: ## if not attempt_read_and_call(uhandle, consumer.matrix, start='MA'): ## line1 = uhandle.readline() ## line2 = uhandle.readline() ## uhandle.saveline(line2) ## uhandle.saveline(line1) ## if line1[:2] == 'CC' and line2[:2] == 'MA': ## read_and_call(uhandle, consumer.comment, start='CC') ## else: ## break def _scan_pp(self, uhandle, consumer): #New PP line, PostProcessing, just after the MA line self._scan_line('PP', uhandle, consumer.postprocessing, any_number=1) def _scan_ru(self, uhandle, consumer): self._scan_line('RU', uhandle, consumer.rule, any_number=1) def _scan_nr(self, uhandle, consumer): self._scan_line('NR', uhandle, consumer.numerical_results, any_number=1) def _scan_cc(self, uhandle, consumer): self._scan_line('CC', uhandle, consumer.comment, any_number=1) def _scan_dr(self, uhandle, consumer): self._scan_line('DR', uhandle, consumer.database_reference, any_number=1) def _scan_3d(self, uhandle, consumer): self._scan_line('3D', uhandle, consumer.pdb_reference, any_number=1) def _scan_pr(self, uhandle, consumer): #New PR line, ProRule, between 3D and DO lines self._scan_line('PR', uhandle, consumer.prorule, any_number=1) def _scan_do(self, uhandle, consumer): self._scan_line('DO', uhandle, consumer.documentation, exactly_one=1) def _scan_terminator(self, uhandle, consumer): self._scan_line('//', uhandle, consumer.terminator, exactly_one=1) #This is a list of scan functions in the order expected in the file file. #The function definitions define how many times each line type is exected #(or if optional): _scan_fns = [ _scan_id, _scan_ac, _scan_dt, _scan_de, _scan_pa, _scan_ma, _scan_pp, _scan_ru, _scan_nr, _scan_cc, # This is a really dirty hack, and should be fixed properly at # some point. ZN2_CY6_FUNGAL_2, DNAJ_2 in Rel 15 and PS50309 # in Rel 17 have lines out of order. Thus, I have to rescan # these, which decreases performance. _scan_ma, _scan_nr, _scan_cc, _scan_dr, _scan_3d, _scan_pr, _scan_do, _scan_terminator ] class _RecordConsumer(AbstractConsumer): """Consumer that converts a Prosite record to a Record object. Members: data Record with Prosite data. """ def __init__(self): self.data = None def start_record(self): self.data = Record() def end_record(self): self._clean_record(self.data) def identification(self, line): cols = line.split() if len(cols) != 3: raise ValueError("I don't understand identification line\n%s" \ % line) self.data.name = self._chomp(cols[1]) # don't want ';' self.data.type = self._chomp(cols[2]) # don't want '.' def accession(self, line): cols = line.split() if len(cols) != 2: raise ValueError("I don't understand accession line\n%s" % line) self.data.accession = self._chomp(cols[1]) def date(self, line): uprline = line.upper() cols = uprline.split() # Release 15.0 contains both 'INFO UPDATE' and 'INF UPDATE' if cols[2] != '(CREATED);' or \ cols[4] != '(DATA' or cols[5] != 'UPDATE);' or \ cols[7][:4] != '(INF' or cols[8] != 'UPDATE).': raise ValueError("I don't understand date line\n%s" % line) self.data.created = cols[1] self.data.data_update = cols[3] self.data.info_update = cols[6] def description(self, line): self.data.description = self._clean(line) def pattern(self, line): self.data.pattern = self.data.pattern + self._clean(line) def matrix(self, line): self.data.matrix.append(self._clean(line)) def postprocessing(self, line): postprocessing = self._clean(line).split(";") self.data.postprocessing.extend(postprocessing) def rule(self, line): self.data.rules.append(self._clean(line)) def numerical_results(self, line): cols = self._clean(line).split(";") for col in cols: if not col: continue qual, data = [word.lstrip() for word in col.split("=")] if qual == '/RELEASE': release, seqs = data.split(",") self.data.nr_sp_release = release self.data.nr_sp_seqs = int(seqs) elif qual == '/FALSE_NEG': self.data.nr_false_neg = int(data) elif qual == '/PARTIAL': self.data.nr_partial = int(data) elif qual in ['/TOTAL', '/POSITIVE', '/UNKNOWN', '/FALSE_POS']: m = re.match(r'(\d+)\((\d+)\)', data) if not m: raise Exception("Broken data %s in comment line\n%s" \ % (repr(data), line)) hits = tuple(map(int, m.groups())) if(qual == "/TOTAL"): self.data.nr_total = hits elif(qual == "/POSITIVE"): self.data.nr_positive = hits elif(qual == "/UNKNOWN"): self.data.nr_unknown = hits elif(qual == "/FALSE_POS"): self.data.nr_false_pos = hits else: raise ValueError("Unknown qual %s in comment line\n%s" \ % (repr(qual), line)) def comment(self, line): #Expect CC lines like this: #CC /TAXO-RANGE=??EPV; /MAX-REPEAT=2; #Can (normally) split on ";" and then on "=" cols = self._clean(line).split(";") for col in cols: if not col or col[:17] == 'Automatic scaling': # DNAJ_2 in Release 15 has a non-standard comment line: # CC Automatic scaling using reversed database # Throw it away. (Should I keep it?) continue if col.count("=") == 0: #Missing qualifier! Can we recover gracefully? #For example, from Bug 2403, in PS50293 have: #CC /AUTHOR=K_Hofmann; N_Hulo continue qual, data = [word.lstrip() for word in col.split("=")] if qual == '/TAXO-RANGE': self.data.cc_taxo_range = data elif qual == '/MAX-REPEAT': self.data.cc_max_repeat = data elif qual == '/SITE': pos, desc = data.split(",") self.data.cc_site.append((int(pos), desc)) elif qual == '/SKIP-FLAG': self.data.cc_skip_flag = data elif qual == '/MATRIX_TYPE': self.data.cc_matrix_type = data elif qual == '/SCALING_DB': self.data.cc_scaling_db = data elif qual == '/AUTHOR': self.data.cc_author = data elif qual == '/FT_KEY': self.data.cc_ft_key = data elif qual == '/FT_DESC': self.data.cc_ft_desc = data elif qual == '/VERSION': self.data.cc_version = data else: raise ValueError("Unknown qual %s in comment line\n%s" \ % (repr(qual), line)) def database_reference(self, line): refs = self._clean(line).split(";") for ref in refs: if not ref: continue acc, name, type = [word.strip() for word in ref.split(",")] if type == 'T': self.data.dr_positive.append((acc, name)) elif type == 'F': self.data.dr_false_pos.append((acc, name)) elif type == 'N': self.data.dr_false_neg.append((acc, name)) elif type == 'P': self.data.dr_potential.append((acc, name)) elif type == '?': self.data.dr_unknown.append((acc, name)) else: raise ValueError("I don't understand type flag %s" % type) def pdb_reference(self, line): cols = line.split() for id in cols[1:]: # get all but the '3D' col self.data.pdb_structs.append(self._chomp(id)) def prorule(self, line): #Assume that each PR line can contain multiple ";" separated rules rules = self._clean(line).split(";") self.data.prorules.extend(rules) def documentation(self, line): self.data.pdoc = self._chomp(self._clean(line)) def terminator(self, line): self.finished = True def _chomp(self, word, to_chomp='.,;'): # Remove the punctuation at the end of a word. if word[-1] in to_chomp: return word[:-1] return word def _clean(self, line, rstrip=1): # Clean up a line. if rstrip: return line[5:].rstrip() return line[5:] def scan_sequence_expasy(seq=None, id=None, exclude_frequent=None): """scan_sequence_expasy(seq=None, id=None, exclude_frequent=None) -> list of PatternHit's Search a sequence for occurrences of Prosite patterns. You can specify either a sequence in seq or a SwissProt/trEMBL ID or accession in id. Only one of those should be given. If exclude_frequent is true, then the patterns with the high probability of occurring will be excluded. """ from Bio import ExPASy if (seq and id) or not (seq or id): raise ValueError("Please specify either a sequence or an id") handle = ExPASy.scanprosite1(seq, id, exclude_frequent) return _extract_pattern_hits(handle) def _extract_pattern_hits(handle): """_extract_pattern_hits(handle) -> list of PatternHit's Extract hits from a web page. Raises a ValueError if there was an error in the query. """ class parser(sgmllib.SGMLParser): def __init__(self): sgmllib.SGMLParser.__init__(self) self.hits = [] self.broken_message = 'Some error occurred' self._in_pre = 0 self._current_hit = None self._last_found = None # Save state of parsing def handle_data(self, data): if data.find('try again') >= 0: self.broken_message = data return elif data == 'illegal': self.broken_message = 'Sequence contains illegal characters' return if not self._in_pre: return elif not data.strip(): return if self._last_found is None and data[:4] == 'PDOC': self._current_hit.pdoc = data self._last_found = 'pdoc' elif self._last_found == 'pdoc': if data[:2] != 'PS': raise ValueError("Expected accession but got:\n%s" % data) self._current_hit.accession = data self._last_found = 'accession' elif self._last_found == 'accession': self._current_hit.name = data self._last_found = 'name' elif self._last_found == 'name': self._current_hit.description = data self._last_found = 'description' elif self._last_found == 'description': m = re.findall(r'(\d+)-(\d+) (\w+)', data) for start, end, seq in m: self._current_hit.matches.append( (int(start), int(end), seq)) def do_hr(self, attrs): # <HR> inside a <PRE> section means a new hit. if self._in_pre: self._current_hit = PatternHit() self.hits.append(self._current_hit) self._last_found = None def start_pre(self, attrs): self._in_pre = 1 self.broken_message = None # Probably not broken def end_pre(self): self._in_pre = 0 p = parser() p.feed(handle.read()) if p.broken_message: raise ValueError(p.broken_message) return p.hits def index_file(filename, indexname, rec2key=None): """index_file(filename, indexname, rec2key=None) Index a Prosite file. filename is the name of the file. indexname is the name of the dictionary. rec2key is an optional callback that takes a Record and generates a unique key (e.g. the accession number) for the record. If not specified, the id name will be used. """ import os if not os.path.exists(filename): raise ValueError("%s does not exist" % filename) index = Index.Index(indexname, truncate=1) index[Dictionary._Dictionary__filename_key] = filename handle = open(filename) records = parse(handle) end = 0L for record in records: start = end end = handle.tell() length = end - start if rec2key is not None: key = rec2key(record) else: key = record.name if not key: raise KeyError("empty key was produced") elif key in index: raise KeyError("duplicate key %s found" % key) index[key] = start, length
BlogomaticProject/Blogomatic
opt/blog-o-matic/usr/lib/python/Bio/Prosite/__init__.py
Python
gpl-2.0
27,006
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.com.orionline.entidade; /** * * @author ronald */ public class BarrasRelacionadas extends ProdutoAUX{ }
ronaldsantos63/ConversorOrionline
src/br/com/orionline/entidade/BarrasRelacionadas.java
Java
gpl-2.0
323
// taikaDlg.cpp : implementation file // #include "stdafx.h" #include "taika.h" #include "taikaDlg.h" #include "Props.h" #include "DlgVarmuuskopioi.h" #include "DlgSiivoaTietokanta.h" #include "DlgAsetukset.h" #include "DlgLuoUusiTietokanta.h" #include "DlgAbout.h" #include "StringHelper_luokka.h" #include <afxpriv.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CTaikaDlg dialog CTaikaDlg::CTaikaDlg(CWnd* pParent /*=NULL*/) : CDialog(CTaikaDlg::IDD, pParent), m_pMenu(NULL) { //{{AFX_DATA_INIT(CTaikaDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CTaikaDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CTaikaDlg) DDX_Control(pDX, IDC_TABMAIN, m_tabMain); DDX_Control(pDX, IDC_SHEET_PLACEHOLDER, m_picPlaceHolder); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CTaikaDlg, CDialog) //{{AFX_MSG_MAP(CTaikaDlg) ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_WM_CLOSE() ON_WM_DESTROY() ON_COMMAND(IDM_AVAA_RAPORTTI, OnAvaaRaportti) ON_COMMAND(IDM_TALLETA_RAPORTTI, OnTalletaRaportti) ON_COMMAND(IDM_VARMUUSKOPIOI_TIETOKANTA, OnVarmuuskopioiTietokanta) ON_COMMAND(IDM_VAIHDA_TIETOKANTA, OnVaihdaTietokanta) ON_COMMAND(IDM_TALLETA_LISTAT, OnTalletaListat) ON_COMMAND(IDM_AVAA_LISTAT, OnAvaaListat) ON_COMMAND(IDM_AVAA_RAPORTTI_TM, OnAvaaRaporttiTm) ON_COMMAND(IDM_TALLETA_RAPORTTI_TM, OnTalletaRaporttiTm) ON_COMMAND(IDM_SIIVOA_TIETOKANTA, OnSiivoaTietokanta) ON_COMMAND(IDM_EMAIL, OnEmail) ON_COMMAND(IDK_VALITSEKAIKKI, OnValitsekaikki) ON_COMMAND(IDK_AVAA, OnAvaa) ON_COMMAND(IDK_TALLETA, OnTalleta) ON_COMMAND(IDK_ETSI, OnEtsi) ON_COMMAND(IDK_ETSI_F3, OnEtsiF3) ON_COMMAND(IDK_UUSI, OnUusi) ON_NOTIFY(TCN_SELCHANGE, IDC_TABMAIN, OnSelchangeTabmain) ON_WM_SIZE() ON_WM_SIZING() ON_COMMAND(IDM_ASETUKSET, OnAsetukset) ON_COMMAND(IDM_LUO_UUSI_TIETOKANTA, OnLuoUusiTietokanta) ON_COMMAND(IDK_IMPORT, OnImport) ON_COMMAND(IDM_TUO_LASKUTUSOHJELMASTA, OnTuoLaskutusohjelmasta) ON_COMMAND(IDK_POISTA_X, OnPoista) ON_COMMAND(IDK_PAIVITA_V5, OnPaivitaV5) ON_COMMAND(IDK_EMAIL, OnEmail) ON_COMMAND(IDM_ABOUT, OnAbout) //}}AFX_MSG_MAP ON_WM_INITMENUPOPUP() ON_MESSAGE(WM_USER_NEW_REPORT, OnMsgUusiRaportti) ON_MESSAGE(WM_IDLEUPDATECMDUI, OnIdleUpdateCmdUI) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CTaikaDlg message handlers LRESULT CTaikaDlg::OnIdleUpdateCmdUI(WPARAM wParam, LPARAM lparam) { return 0L; } BOOL CTaikaDlg::OnInitDialog() { int ret; RECT trect, crect; TCITEM tci; CString cs; DbSqlite db; Parse parse; CRect rcSheet; string use_db; CDialog::OnInitDialog(); SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // Päällimmäisin dialogi - aluksi raportit m_mainShowMode = SHOW_RAPORTIT; // Kansiot - luo kansiot, jos niitä ei löydy luoKansiot(Props::e().m_app_path); // Asetukset - luo perusasetukset, jos ei löydy if(Props::i().get(OPTIONS_AIKAJARJESTYS_R) == "") { use_db = Props::e().m_app_path + DEFAULT_DB_NAME; Props::i().set(OPTIONS_DB_PATH, use_db); Props::i().set(OPTIONS_DB_NAME, DEFAULT_DB_NAME); Props::i().set(OPTIONS_AUTOPARSE, "TRUE"); Props::i().set(OPTIONS_LASKUTUSOHJELMA, LAS_NONE); Props::i().set(OPTIONS_LASKUTUSOHJELMA_POLKU, "c:\\"); Props::i().set(OPTIONS_LASKUTUSOHJELMA_KOKO_POLKU, ""); Props::i().set(OPTIONS_KAYNTIKERTAVELOITUS, C_TRUE); Props::i().set(OPTIONS_HINNAT, HINNAT_LASKOHJ); Props::i().set(OPTIONS_LASKUTUSTILA, LTILA_LASKUTTAMATTOMAT); Props::i().set(OPTIONS_LASKUNMAKSUAIKA, "30"); Props::i().set(OPTIONS_YHDISTATAPAHTUMAT, C_TRUE); Props::i().set(OPTIONS_OPENPATH, (LPCSTR)Props::e().m_app_path); Props::i().set(OPTIONS_SAVEPATH, (LPCSTR)Props::e().m_app_path); Props::i().set(OPTIONS_AJAT, StringHelper::itoa(TIME_MINUTES, 10)); Props::i().set(OPTIONS_ALKAEN_R, DATE_VANHIN_TYO); Props::i().set(OPTIONS_PAATTYEN_R, DATE_UUSIN_TYO); Props::i().set(OPTIONS_ALKAEN_VIIMEISIN_R, "1.1.2008"); Props::i().set(OPTIONS_PAATTYEN_VIIMEISIN_R, "1.1.2008"); Props::i().set(OPTIONS_ALKAEN_T, DATE_VANHIN_TYO); Props::i().set(OPTIONS_PAATTYEN_T, DATE_UUSIN_TYO); Props::i().set(OPTIONS_ALKAEN_VIIMEISIN_T, "1.1.2008"); Props::i().set(OPTIONS_PAATTYEN_VIIMEISIN_T, "1.1.2008"); Props::i().set(OPTIONS_AIKAJARJESTYS_R, DESCENT_S); Props::i().set(OPTIONS_AIKAJARJESTYS_T, DESCENT_S); Props::i().set(OPTIONS_KMKERROIN, "0.43"); use_db = Props::e().m_app_path + "varmuuskopiot\\"; Props::i().set(OPTIONS_DB_BACKUP_PATH, use_db); Props::i().set(OPTIONS_EM_RECIPIENTS, ""); Props::i().set(OPTIONS_EM_FROM, ""); Props::i().set(OPTIONS_EM_SMTP_SERVER, ""); Props::i().set(OPTIONS_EM_SMTP_PORT, "25"); Props::i().set(OPTIONS_PRNT_ASNIMI, PRNT_ASNIMINRO); Props::i().set(OPTIONS_PRNT_ASALOITUSPVM, PRNT_PVM_AIKA); Props::i().set(OPTIONS_PRNT_ASLOPETUSPVM, PRNT_PVM_AIKA); Props::i().set(OPTIONS_PRNT_ASTYOAIKA, PRNT_TYOAIKA_MIN); Props::i().set(OPTIONS_PRNT_ASTYOTYYPIT, PRNT_TYOTYYPIT); Props::i().set(OPTIONS_PRNT_TTALOITUSPVM, PRNT_PVM_AIKA); Props::i().set(OPTIONS_PRNT_TTLOPETUSPVM, PRNT_PVM_AIKA); Props::i().set(OPTIONS_PRNT_TTTYOAIKA, PRNT_TYOAIKA_MIN); Props::i().set(OPTIONS_PRNT_TTTYOTYYPIT, PRNT_TYOTYYPIT); Props::i().set(OPTIONS_PRNT_TMPAIVAYKSET, PRNT_PVM_AIKA_MOLEMMAT); Props::i().set(OPTIONS_PRNT_TMMATKA, PRNT_MATKAT_TARKOITUS); Props::i().set(OPTIONS_PRNT_TMLUKEMAT, PRNT_LUKEMAT); Props::i().set(OPTIONS_PRNT_TMYKSAJOA, PRNT_YKSAJOA); Props::i().set(OPTIONS_PRNT_TMTYOAJOA, PRNT_TYOAJOA); Props::i().set(OPTIONS_PRNT_SIVUTUS, C_TRUE); Props::i().set(OPTIONS_PRNT_YLATUNNISTE_TEXT, ""); Props::i().set(OPTIONS_PRNT_ALATUNNISTE_TEXT, ""); Props::i().set(OPTIONS_PRNT_YLATUNNISTE, C_TRUE); Props::i().set(OPTIONS_PRNT_ALATUNNISTE, C_TRUE); Props::i().set(OPTIONS_PRNT_YLAPAIVAYS, C_TRUE); Props::i().set(OPTIONS_PRNT_FONTINKOKO, FONTSIZE_8); Props::i().set(OPTIONS_PRNT_FONTINNIMI, "Arial"); Props::i().set(OPTIONS_PRNT_YHTEENVETO, C_TRUE); Props::i().set(OPTIONS_PRNT_KMKORVAUS, C_TRUE); Props::i().set(OPTIONS_PRNT_YHDISTATAPAHTUMAT, C_TRUE); Props::i().set(OPTIONS_EM_SMTP_USE_AUTH, C_FALSE); Props::i().set(OPTIONS_EM_SMTP_RMBR_UN, C_FALSE); Props::i().set(OPTIONS_EM_SMTP_USERNAME, ""); Props::i().set(OPTIONS_LSTHEADER_RATA, ""); Props::i().set(OPTIONS_LSTHEADER_RAMY, ""); Props::i().set(OPTIONS_LSTHEADER_LIAR, ""); Props::i().set(OPTIONS_LSTHEADER_LIAS, ""); Props::i().set(OPTIONS_LSTHEADER_LILA, ""); Props::i().set(OPTIONS_LSTHEADER_LITT, ""); Props::i().set(OPTIONS_LSTHEADER_LITR, ""); Props::i().set(OPTIONS_LSTHEADER_LITU, ""); Props::i().set(OPTIONS_LSTHEADER_TYTY, ""); } // Otetaan tietokannan polku asetuksista, Tarkistetaan tietokanta (luodaan, jos ei ole olemassa) Props::e().m_db_path = Props::i().get(OPTIONS_DB_PATH).c_str(); if((ret = db.check()) != RETURN_OK) Props::e().m_db_path = ""; // Virheen sattuessa, ei tietokantaa!!! //EndDialog(IDCANCEL); // Tarkistetaan onko saapuneet kansiossa uusia raportteja if(ret == RETURN_OK) parse.parseSaapuneet(PARSE_SAAPUNEET); // Dialogin otsikko resurssista ja tietokannan nimi asetuksista usedDB(); // Menu paikoilleen (aluksi IDR_RAPORTIT_MENU, asetetaan eri dilogeissa vastaamaan paremmin niiden toimintoja) m_pMenu = pageRaportit.createMenu(); this->SetMenu(m_pMenu); AfxGetMainWnd()->DrawMenuBar(); // Koko ruutu ShowWindow(SW_MAXIMIZE); // Alustetaan tab-kontolli GetClientRect(&crect); m_tabMain.SetWindowPos(NULL, 0, 0, crect.right, crect.bottom, SWP_NOMOVE|SWP_NOZORDER); tci.mask = TCIF_IMAGE|TCIF_TEXT; tci.iImage = 0; tci.pszText = (LPSTR)(LPCSTR)Props::i().lang("TAIKADLG_1"); m_tabMain.InsertItem(0, &tci); tci.mask = TCIF_IMAGE|TCIF_TEXT; tci.iImage = 0; tci.pszText = (LPSTR)(LPCSTR)Props::i().lang("TAIKADLG_2"); m_tabMain.InsertItem(1, &tci); tci.mask = TCIF_IMAGE|TCIF_TEXT; tci.iImage = 0; tci.pszText = (LPSTR)(LPCSTR)Props::i().lang("TAIKADLG_3"); m_tabMain.InsertItem(2, &tci); // Placeholder ylänurkkaan m_tabMain.GetItemRect(0, &trect); // tabin headerin koko m_tabMain.GetClientRect(&crect); // tabin koko m_picPlaceHolder.SetWindowPos(NULL, PAGE_LEFT, PAGE_TOP + trect.bottom, crect.right - PAGE_LEFT - PAGE_RIGHT, crect.bottom - trect.bottom - PAGE_TOP - PAGE_BOTTOM, SWP_NOZORDER); // Luo dialogit pageRaportit.CRHCreateGenericChildDialog(this, IDC_SHEET_PLACEHOLDER, 0, NULL); pageListat.CRHCreateGenericChildDialog(this, IDC_SHEET_PLACEHOLDER, 0, NULL); pageTyomatkat.CRHCreateGenericChildDialog(this, IDC_SHEET_PLACEHOLDER, 0, NULL); // Ja uudestaan menu - dialogien luonti voi sotkea näytettävän menun if(m_pMenu) m_pMenu->DestroyMenu(); m_pMenu = pageRaportit.createMenu(); this->SetMenu(m_pMenu); AfxGetMainWnd()->DrawMenuBar(); return TRUE; // return TRUE unless you set the focus to a control } void CTaikaDlg::OnClose() { CDialog::OnClose(); } void CTaikaDlg::OnDestroy() { CDialog::OnDestroy(); if(m_pMenu) m_pMenu->DestroyMenu(); // Tuhoa menu } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CTaikaDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } HCURSOR CTaikaDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } BOOL CTaikaDlg::PreTranslateMessage(MSG* pMsg) { if(pMsg->message == WM_KEYDOWN) // Estetään RETURNIN painaminen dialogissa (dialogi ei sulkeudu vahingossa) { if(pMsg->wParam == VK_RETURN) return TRUE; } SendMessageToDescendants(WM_KICKIDLE, 0, 0, FALSE, FALSE); return CDialog::PreTranslateMessage(pMsg); } void CTaikaDlg::OnOK() {} void CTaikaDlg::OnCancel() { CDialog::OnCancel(); } void CTaikaDlg::OnSize(UINT nType, int cx, int cy) { BOOL resize = FALSE; RECT crect, trect; int page_width, page_height; // Varmista, että ikkunat on luotu if(this->GetSafeHwnd() == 0) return; if(m_tabMain.GetSafeHwnd() == 0) return; if(m_picPlaceHolder.GetSafeHwnd() == 0) return; CDialog::OnSize(nType, cx, cy); // tab-control ruudun kokoiseksi GetClientRect(&crect); m_tabMain.SetWindowPos(NULL, 0, 0, crect.right, crect.bottom, SWP_NOMOVE|SWP_NOZORDER); // placeholder tabin kokoiseksi m_tabMain.GetItemRect(0, &trect); // tabin headerin koko m_tabMain.GetClientRect(&crect); // tabin koko page_width = crect.right - PAGE_LEFT - PAGE_RIGHT; // sivun koko: w = tabin w - marginaalit, h = tabin h - tabin h - marginaalit page_height = crect.bottom - trect.bottom - PAGE_TOP - PAGE_BOTTOM; m_picPlaceHolder.SetWindowPos(NULL, 0, 0, page_width, page_height, SWP_NOMOVE|SWP_NOZORDER); // Muuta lapsidialogien koot if(pageRaportit.GetSafeHwnd() != NULL) pageRaportit.windowSize(); if(pageListat.GetSafeHwnd() != NULL) pageListat.windowSize(); if(pageTyomatkat.GetSafeHwnd() != NULL) pageTyomatkat.windowSize(); } void CTaikaDlg::OnSizing(UINT nSide, LPRECT lpRect) { if(lpRect->right - lpRect->left < 890) lpRect->right = lpRect->left + 890; if(lpRect->bottom - lpRect->top < 500) lpRect->bottom = lpRect->top + 500; } // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // Komentojen käsittelijät // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // void CTaikaDlg::OnSelchangeTabmain(NMHDR* pNMHDR, LRESULT* pResult) { int sel = m_tabMain.GetCurSel(); if(sel == 0 && m_mainShowMode != SHOW_RAPORTIT) { m_mainShowMode = SHOW_RAPORTIT; pageRaportit.ShowWindow(SW_SHOW); pageListat.ShowWindow(SW_HIDE); pageTyomatkat.ShowWindow(SW_HIDE); pageRaportit.OnSetActive(); } else if(sel == 1) { m_mainShowMode = SHOW_LISTAT; pageRaportit.ShowWindow(SW_HIDE); pageListat.ShowWindow(SW_SHOW); pageTyomatkat.ShowWindow(SW_HIDE); pageListat.OnSetActive(); } else if(sel == 2) { m_mainShowMode = SHOW_TYOMATKAT; pageRaportit.ShowWindow(SW_HIDE); pageListat.ShowWindow(SW_HIDE); pageTyomatkat.ShowWindow(SW_SHOW); pageTyomatkat.OnSetActive(); } *pResult = 0; } LRESULT CTaikaDlg::OnMsgUusiRaportti(WPARAM wparam, LPARAM lparam) { //int s; Parse parse; this->BringWindowToTop(); parse.parseSaapuneet(PARSE_ADD_FILE); // Parsitaan saapuneet lista ja päivitetään näytöt if(wparam == PARAM_TTI || wparam == PARAM_TTA) paivitaNaytot(TRUE, TRUE, FALSE, SYNC_ALL); return 0; } void CTaikaDlg::luoKansiot(CString app_path) { // Luo kansiot jos niitä ei löydy WIN32_FIND_DATA fd; HANDLE hfile = NULL; CString dirpath, cs; dirpath = app_path + "saapuneet\\"; if((hfile = FindFirstFile(dirpath, &fd)) != INVALID_HANDLE_VALUE) FindClose(hfile); else { if(GetLastError() == ERROR_PATH_NOT_FOUND) CreateDirectory(dirpath, NULL); } dirpath = app_path + "raportit\\"; if((hfile = FindFirstFile(dirpath, &fd)) != INVALID_HANDLE_VALUE) FindClose(hfile); else { if(GetLastError() == ERROR_PATH_NOT_FOUND) CreateDirectory(dirpath, NULL); } dirpath = app_path + "varmuuskopiot\\"; if((hfile = FindFirstFile(dirpath, &fd)) != INVALID_HANDLE_VALUE) FindClose(hfile); else { if(GetLastError() == ERROR_PATH_NOT_FOUND) CreateDirectory(dirpath, NULL); } } ///////////////////////////////////////////////////////////////////////////// // Menun itemien disablointi/enablointi logiikka void CTaikaDlg::OnInitMenuPopup(CMenu* pPopupMenu, UINT nIndex, BOOL bSysMenu) { if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) setRaporttiMenu(nIndex); if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) setListatMenu(nIndex); } void CTaikaDlg::setRaporttiMenu(UINT nIndex) { int flags; CMenu *pMenu = this->GetMenu(); if(nIndex == 0) // Tiedosto-menu { // IDM_TALLETA_RAPORTTI if(pageRaportit.m_lstAsiakkaat.GetSelCount() > 0 || pageRaportit.m_plstRaportit->GetItemCount() > 0) flags = MF_ENABLED; else flags = MF_DISABLED|MF_GRAYED; pMenu->EnableMenuItem(IDM_TALLETA_RAPORTTI, flags); } } void CTaikaDlg::setListatMenu(UINT nIndex) {} ///////////////////////////////////////////////////////////////////////////// // IDM_RAPORTIT_MENU - Menu itemien viestit void CTaikaDlg::OnAvaaRaportti() { //int s; Parse parse; if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) // Avaa .tti-tiedosto { if(!parse.avaaTTI(this->GetSafeHwnd())) return; } paivitaNaytot(TRUE, TRUE, FALSE, SYNC_ALL); } void CTaikaDlg::OnTalletaRaportti() { Parse parse; if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) // Talleta valitut ID_WORKUNIT/ID_SALESUNIT-tiedostoon (.tta) { parse.talletaTTI(this->GetSafeHwnd(), pageRaportit.getMode()); } } void CTaikaDlg::OnEmail() { Parse parse; //if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) pageRaportit.email(); if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) pageListat.email(); } void CTaikaDlg::OnAbout() { CDlgAbout dlga; dlga.DoModal(); } ///////////////////////////////////////////////////////////////////////////// // IDM_LISTAT_MENU - Menu itemien viestit void CTaikaDlg::OnAvaaListat() { Parse parse; if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) // Avaa .tta-tiedosto { if(!parse.avaaTTA(this->GetSafeHwnd())) return; } paivitaNaytot(FALSE, FALSE, FALSE, SYNC_ALL); } void CTaikaDlg::OnTalletaListat() { Parse parse; if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) // Talleta listat { parse.talletaTTA(this->GetSafeHwnd(), "", 0, 0, 0, 0, MODE_SAVE); } } void CTaikaDlg::OnTuoLaskutusohjelmasta() { OnImport(); } ///////////////////////////////////////////////////////////////////////////// // IDM_TYOMATKAT_MENU - Menu itemien viestit void CTaikaDlg::OnAvaaRaporttiTm() { //int s; Parse parse; if(m_mainShowMode == SHOW_TYOMATKAT && pageTyomatkat.IsWindowVisible()) // Avaa .tti-tiedosto { if(!parse.avaaTTI(this->GetSafeHwnd())) return; } paivitaNaytot(TRUE, TRUE, FALSE, SYNC_ALL); } void CTaikaDlg::OnTalletaRaporttiTm() { Parse parse; vector <ItemData_travel*> id_vect; // Haetaan GetSaveFileName()-funktiossa valitun tilan mukaan vektoriin talletettavat tiedot if(m_mainShowMode != SHOW_TYOMATKAT || !pageTyomatkat.IsWindowVisible()) return; pageTyomatkat.haeItemDataList(&id_vect, MODE_TYONTEKIJANTIEDOT); if(id_vect.size() > 0) { parse.talletaTTI_tyomatkat(this->GetSafeHwnd(), id_vect); // Talletetaan pageTyomatkat.vapautaItemDataList(&id_vect, MODE_TYONTEKIJANTIEDOT); // Vapautetaan muisti } } ///////////////////////////////////////////////////////////////////////////// // IDM_RAPORTIT_MENU, IDM_LISTAT_MENU, IDM_ASETUKSET - Menu itemien yhteiset viestit void CTaikaDlg::OnVarmuuskopioiTietokanta() { DlgVarmuuskopioi dlg; if(dlg.DoModal() == IDOK) paivitaNaytot(TRUE, TRUE, FALSE, SYNC_ALL); } void CTaikaDlg::OnVaihdaTietokanta() { DWORD e; CString file; char buf[128] = {0}; OPENFILENAME ofn; DlgParseInfo dlg; char *lpstrFile = NULL, strFileTitle[MAX_PATH]; try { file = Props::i().get(OPTIONS_DB_PATH).c_str(); if(!(lpstrFile = new char[MAX_PATH * 100])) throw(0); // Tarpeeksi tilaa useammalle tiedostonimelle ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = this->GetSafeHwnd(); ofn.lpstrFilter = Props::i().langs("TAIKADLG_4", buf, 128); ofn.lpstrTitle = Props::i().lang("TAIKADLG_5"); ofn.lpstrInitialDir = file; ofn.lpstrCustomFilter = NULL; ofn.nFilterIndex = 1; *lpstrFile = NULL; ofn.lpstrFile = lpstrFile; ofn.nMaxFile = MAX_PATH * 100; ofn.lpstrFileTitle = strFileTitle; ofn.nMaxFileTitle = MAX_PATH; ofn.Flags = OFN_EXPLORER|OFN_HIDEREADONLY|OFN_LONGNAMES|OFN_PATHMUSTEXIST; ofn.lpstrDefExt = NULL; ofn.lCustData = NULL; if(!GetOpenFileName(&ofn)) throw(0); Props::i().set(OPTIONS_DB_PATH, ofn.lpstrFile); // talleta, mahdollisesti uusi, polku asetuksiin Props::i().set(OPTIONS_DB_NAME, (char*)(ofn.lpstrFile + ofn.nFileOffset)); Props::e().m_db_path = ofn.lpstrFile; paivitaNaytot(TRUE, TRUE, TRUE, SYNC_ALL); } catch(...) { if((e = CommDlgExtendedError()) != ERROR_SUCCESS) { file.Format(Props::i().lang("TAIKADLG_6"), e); MessageBox(file, Props::e().m_app_title, MB_ICONEXCLAMATION|MB_TASKMODAL|MB_TOPMOST|MB_OK); } } if(lpstrFile) delete [] lpstrFile; } void CTaikaDlg::OnAsetukset() { CDlgAsetukset dlg; dlg.DoModal(); } void CTaikaDlg::OnLuoUusiTietokanta() { CDlgLuoUusiTietokanta dlg; if(dlg.DoModal() == IDOK) paivitaNaytot(TRUE, TRUE, TRUE, SYNC_ALL); } void CTaikaDlg::OnSiivoaTietokanta() { DlgSiivoaTietokanta dlg; if(dlg.DoModal() == IDOK) paivitaNaytot(TRUE, TRUE, FALSE, SYNC_ALL); } // Accelerator-näppäimet (kaasutusnäppäimet) void CTaikaDlg::OnValitsekaikki() { if(GetForegroundWindow() != this) GetForegroundWindow()->PostMessage(WM_USER_SELECTALL); else { if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) pageRaportit.valitseKaikki(); if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) pageListat.valitseKaikki(); if(m_mainShowMode == SHOW_TYOMATKAT && pageTyomatkat.IsWindowVisible()) pageTyomatkat.valitseKaikki(); } } void CTaikaDlg::OnAvaa() { if(GetForegroundWindow() == this) { if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) OnAvaaRaportti(); if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) OnAvaaListat(); if(m_mainShowMode == SHOW_TYOMATKAT && pageTyomatkat.IsWindowVisible()) OnAvaaRaporttiTm(); } } void CTaikaDlg::OnTalleta() { if(GetForegroundWindow() == this) { if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) OnTalletaRaportti(); if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) OnTalletaListat(); if(m_mainShowMode == SHOW_TYOMATKAT && pageTyomatkat.IsWindowVisible()) OnTalletaRaporttiTm(); } } void CTaikaDlg::OnEtsi() { if(GetForegroundWindow() == this) { if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) pageRaportit.etsi(KEY_CTRLF); if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) pageListat.etsi(KEY_CTRLF); } } void CTaikaDlg::OnEtsiF3() { if(GetForegroundWindow() == this) { if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) pageRaportit.etsi(KEY_F3); if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) pageListat.etsi(KEY_F3); } } void CTaikaDlg::OnPoista() { poista(); } BOOL CTaikaDlg::poista() { if(GetForegroundWindow() == this) { if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) pageRaportit.poistaItems(); if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) pageListat.poista(); if(m_mainShowMode == SHOW_TYOMATKAT && pageTyomatkat.IsWindowVisible()) pageTyomatkat.poistaValitut(); return TRUE; } return FALSE; } void CTaikaDlg::OnUusi() { if(GetForegroundWindow() == this) { if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) pageRaportit.lisaaTapahtuma(0); if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) pageListat.lisaa(); if(m_mainShowMode == SHOW_TYOMATKAT && pageTyomatkat.IsWindowVisible()) pageTyomatkat.lisaaUusi(0); } } void CTaikaDlg::OnImport() { if(GetForegroundWindow() == this) { if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) { if(pageListat.importListat() == IDOK) paivitaNaytot(TRUE, FALSE, FALSE, SYNC_ALL); } } } void CTaikaDlg::OnPaivitaV5() { if(GetForegroundWindow() == this) paivitaNaytot(TRUE, TRUE, TRUE, SYNC_ALL); } // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // Yhteiset funktiot // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // void CTaikaDlg::paivitaNaytot(BOOL date, BOOL select, BOOL database, int type) { // Keskitetty näyttöjen päivitys if(m_mainShowMode == SHOW_RAPORTIT) { pageRaportit.paivitaAARListat("", NULL, FALSE); pageRaportit.paivitaTyontekijat("", NULL, FALSE); pageRaportit.paivitaTyotyyppi("", NULL, FALSE); pageRaportit.paivitaPaivays(0, "", NULL, FALSE); if(date) pageRaportit.paivitaPaivays(0, "", NULL, FALSE); if(select) pageRaportit.uusiHaku(NULL); syncListat(SYNC_FROM_RAPORTIT, type); } if(m_mainShowMode == SHOW_LISTAT) { pageListat.paivitaAsiakasryhmat("", TRUE); pageListat.paivitaAsiakkaat(""); pageListat.paivitaTila(); syncListat(SYNC_FROM_LISTAT, type); } if(m_mainShowMode == SHOW_TYOMATKAT) { pageTyomatkat.paivitaTyontekijat("", NULL, FALSE); pageTyomatkat.paivitaPaivays(0, "", NULL, FALSE); if(date) pageTyomatkat.paivitaPaivays(0, "", NULL, FALSE); if(select) pageTyomatkat.uusiHaku(NULL); syncListat(SYNC_FROM_TYOMATKAT, type); } if(database) usedDB(); } void CTaikaDlg::syncListat(int from, int type) { // Listojen muutokset heijastuu kaikkien eri näyttöjen listoihin -> välitä tieto päivityksestä näytöille if(from != SYNC_FROM_RAPORTIT) Props::e().m_sync_raportit |= type; if(from != SYNC_FROM_LISTAT) Props::e().m_sync_listat |= type; if(from != SYNC_FROM_TYOMATKAT) Props::e().m_sync_tyomatkat |= type; // Etsi-toiminnon vanhat osumat poistetaan, jos asiakkaat muuttuneet if((type&SYNC_ASIAKKAAT) || (type&SYNC_ASIAKASRYHMAT)) Props::e().m_dlgEtsi.clear(); } void CTaikaDlg::usedDB() { CString cs; cs = Props::i().lang("APPNAME") + CString(" - ") + Props::i().get(OPTIONS_DB_NAME).c_str(); this->SetWindowText(cs); }
ptesavol/t-time
VS2005App/taikaDlg.cpp
C++
gpl-2.0
25,345
// Generated by CoffeeScript 1.8.0 (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; (function(jQuery) { var $, $event, AwesomeGallery, CustomAdapter, FooBoxAdapter, GalleryFilters, JetpackAdapter, LightboxAdapter, MagnificPopupAdapter, Modernizr, PrettyPhotoAdapter, SwipeboxAdapter, capitalize, classes, dispatchMethod, document, getStyleProperty, iLightboxAdapter, prefixes, resizeTimeout, result, setIsoTransform, testName, tests, transformFnNotations, transformProp, transitionDurProp, transitionEndEvent, transitionProp; if (!jQuery) { return alert('Message from UberGrid: jQuery not found!'); } else { if (parseInt(jQuery().jquery.replace(/\./g, '')) < 172) { return alert('Message from Awesome Gallery: You have jQuery < 1.7.2. Please upgrade your jQuery or enable "Force new jQuery version" option at Awesome Gallery settings page.'); } else { $ = jQuery; document = window.document; Modernizr = window.Modernizr; transitionEndEvent = null; capitalize = function(str) { return str.charAt(0).toUpperCase() + str.slice(1); }; prefixes = "Moz Webkit O Ms".split(" "); getStyleProperty = function(propName) { var i, len, prefixed, style; style = document.documentElement.style; prefixed = void 0; if (typeof style[propName] === "string") { return propName; } propName = capitalize(propName); i = 0; len = prefixes.length; while (i < len) { prefixed = prefixes[i] + propName; if (typeof style[prefixed] === "string") { return prefixed; } i++; } }; transformProp = getStyleProperty("transform"); transitionProp = getStyleProperty("transitionProperty"); tests = { csstransforms: function() { return !!transformProp; }, csstransforms3d: function() { var $div, $style, mediaQuery, test, vendorCSSPrefixes; test = !!getStyleProperty("perspective"); if (test) { vendorCSSPrefixes = " -o- -moz- -ms- -webkit- -khtml- ".split(" "); mediaQuery = "@media (" + vendorCSSPrefixes.join("transform-3d),(") + "modernizr)"; $style = $("<style>" + mediaQuery + "{#modernizr{height:3px}}" + "</style>").appendTo("head"); $div = $("<div id=\"modernizr\" />").appendTo("html"); test = $div.height() === 3; $div.remove(); $style.remove(); } return test; }, csstransitions: function() { return !!transitionProp; } }; testName = void 0; if (Modernizr) { for (testName in tests) { if (!Modernizr.hasOwnProperty(testName)) { Modernizr.addTest(testName, tests[testName]); } } } else { Modernizr = window.Modernizr = { _version: "1.6ish: miniModernizr for Isotope" }; classes = " "; result = void 0; for (testName in tests) { result = tests[testName](); Modernizr[testName] = result; classes += " " + (result ? "" : "no-") + testName; } $("html").addClass(classes); } /* provides hooks for .css({ scale: value, translate: [x, y] }) Progressively enhanced CSS transforms Uses hardware accelerated 3D transforms for Safari or falls back to 2D transforms. */ if (Modernizr.csstransforms) { transformFnNotations = (Modernizr.csstransforms3d ? { translate: function(position) { return "translate3d(" + position[0] + "px, " + position[1] + "px, 0) "; }, scale: function(scale) { return "scale3d(" + scale + ", " + scale + ", 1) "; } } : { translate: function(position) { return "translate(" + position[0] + "px, " + position[1] + "px) "; }, scale: function(scale) { return "scale(" + scale + ") "; } }); setIsoTransform = function(elem, name, value) { var data, fnName, newData, scaleFn, transformObj, transformValue, translateFn, valueFns; data = $.data(elem, "isoTransform") || {}; newData = {}; fnName = void 0; transformObj = {}; transformValue = void 0; newData[name] = value; $.extend(data, newData); for (fnName in data) { transformValue = data[fnName]; transformObj[fnName] = transformFnNotations[fnName](transformValue); } translateFn = transformObj.translate || ""; scaleFn = transformObj.scale || ""; valueFns = translateFn + scaleFn; $.data(elem, "isoTransform", data); elem.style[transformProp] = valueFns; }; $.cssNumber.scale = true; $.cssHooks.scale = { set: function(elem, value) { setIsoTransform(elem, "scale", value); }, get: function(elem, computed) { var transform; transform = $.data(elem, "isoTransform"); if (transform && transform.scale) { return transform.scale; } else { return 1; } } }; $.fx.step.scale = function(fx) { $.cssHooks.scale.set(fx.elem, fx.now + fx.unit); }; $.cssNumber.translate = true; $.cssHooks.translate = { set: function(elem, value) { setIsoTransform(elem, "translate", value); }, get: function(elem, computed) { var transform; transform = $.data(elem, "isoTransform"); if (transform && transform.translate) { return transform.translate; } else { return [0, 0]; } } }; } transitionEndEvent = void 0; transitionDurProp = void 0; if (Modernizr.csstransitions) { transitionEndEvent = { WebkitTransitionProperty: "webkitTransitionEnd", MozTransitionProperty: "transitionend", OTransitionProperty: "oTransitionEnd otransitionend", transitionProperty: "transitionend" }; [ { transitionProp: transitionProp } ]; transitionDurProp = getStyleProperty("transitionDuration"); } $event = $.event; dispatchMethod = ($.event.handle ? "handle" : "dispatch"); resizeTimeout = void 0; $event.special.smartresize = { setup: function() { $(this).bind("resize", $event.special.smartresize.handler); }, teardown: function() { $(this).unbind("resize", $event.special.smartresize.handler); }, handler: function(event, execAsap) { var args, context; context = this; args = arguments; event.type = "smartresize"; if (resizeTimeout) { clearTimeout(resizeTimeout); } resizeTimeout = setTimeout(function() { $event[dispatchMethod].apply(context, args); }, (execAsap === "execAsap" ? 0 : 100)); } }; $.fn.smartresize = function(fn) { if (fn) { return this.bind("smartresize", fn); } else { return this.trigger("smartresize", ["execAsap"]); } }; LightboxAdapter = (function() { LightboxAdapter.create = function($images, config) { switch (config.name) { case 'magnific-popup': return new MagnificPopupAdapter($images, config); case 'swipebox': return new SwipeboxAdapter($images, config); case 'prettyphoto': return new PrettyPhotoAdapter($images, config); case 'ilightbox': return new iLightboxAdapter($images, config); case 'jetpack': return new JetpackAdapter($images, config); case 'foobox': return new FooBoxAdapter($images, config); default: return null; } }; function LightboxAdapter($el, config) { this.onPrevSlide = __bind(this.onPrevSlide, this); this.onNextSlide = __bind(this.onNextSlide, this); this.onAfterClose = __bind(this.onAfterClose, this); this.onKeyUp = __bind(this.onKeyUp, this); this.setHash = __bind(this.setHash, this); this.getInstanceIndex = __bind(this.getInstanceIndex, this); this.onImageClicked = __bind(this.onImageClicked, this); this.getLightboxCaption2 = __bind(this.getLightboxCaption2, this); this.getLightboxCaption1 = __bind(this.getLightboxCaption1, this); this.getSlug = __bind(this.getSlug, this); this.getId = __bind(this.getId, this); this.getAllLightboxLinks = __bind(this.getAllLightboxLinks, this); this.getLightboxLinks = __bind(this.getLightboxLinks, this); this.getDeeplinkImage = __bind(this.getDeeplinkImage, this); this.clickImage = __bind(this.clickImage, this); this.loadDeepLink = __bind(this.loadDeepLink, this); this.checkForDeeplink = __bind(this.checkForDeeplink, this); this.addImages = __bind(this.addImages, this); this.reset = __bind(this.reset, this); this.$el = $el; this.config = config; this.getAllLightboxLinks().off('click').removeClass('prettyphoto').removeClass('thickbox'); setTimeout(this.reset, 1); this.reset(); this.checkForDeeplink(); } LightboxAdapter.prototype.reset = function() { this.getAllLightboxLinks().off('click', this.onImageClicked); return this.getLightboxLinks().on('click', this.onImageClicked); }; LightboxAdapter.prototype.addImages = function(images) { return this.reset(); }; LightboxAdapter.prototype.checkForDeeplink = function() { var gridId, image; if (location.hash.match(/^#\d+\-/)) { gridId = location.hash.replace(/^\#/, '').replace(/\-.*/, ''); if (gridId !== this.getId()) { return false; } image = location.hash.replace(/^.*\//, ''); this.loadDeepLink(image); return true; } }; LightboxAdapter.prototype.loadDeepLink = function(image) { var linkedImage; linkedImage = this.getDeeplinkImage(image); if (linkedImage.length > 0) { return this.clickImage(linkedImage); } else { return this.config.loadMoreCallback(); } }; LightboxAdapter.prototype.clickImage = function(image) { return $(image).find('a.asg-lightbox').click(); }; LightboxAdapter.prototype.getDeeplinkImage = function(id) { return jQuery.grep(this.getLightboxLinks().closest('.asg-image'), (function(_this) { return function(cell) { return $(cell).data('slug').toString() === id; }; })(this)); }; LightboxAdapter.prototype.linkSelector = '.asg-image:not(.asg-hidden) .asg-image-wrapper.asg-lightbox'; LightboxAdapter.prototype.allLinkSelector = '.asg-image .asg-image-wrapper.asg-lightbox'; LightboxAdapter.prototype.getLightboxLinks = function() { return this.$el.find(this.linkSelector); }; LightboxAdapter.prototype.getAllLightboxLinks = function() { return this.$el.find(this.allLinkSelector); }; LightboxAdapter.prototype.getId = function() { return this.$el.parent().attr('id').replace(/\-\d+$/, '').replace(/^.*\-/, ''); }; LightboxAdapter.prototype.getSlug = function() { return this.$el.parent().attr('data-slug'); }; LightboxAdapter.prototype.getLightboxCaption1 = function(el) { var caption_1; if (caption_1 = el.find('.asg-lightbox-caption1').html()) { caption_1 = $('<h3 />').html(caption_1)[0].outerHTML; } else { caption_1 = ''; } return caption_1; }; LightboxAdapter.prototype.getLightboxCaption2 = function(el) { var caption_2; if (caption_2 = el.find('.asg-lightbox-caption2').html()) { caption_2 = $('<div />').html(caption_2)[0].outerHTML; } else { caption_2 = ''; } return caption_2; }; LightboxAdapter.prototype.onImageClicked = function(event) { var cell; cell = jQuery(event.target).closest('.asg-image'); this.scrollTop = jQuery(document).scrollTop(); return this.setHash(cell); }; LightboxAdapter.prototype.getID = function() { return this.$el.parent().attr('id').replace(/\-\d+$/, '').replace(/.+\-/, ''); }; LightboxAdapter.prototype.getInstanceIndex = function() { return this.$el.parent().attr('id').replace(/.*\-/, ''); }; LightboxAdapter.prototype.setHash = function(cell) { var cellSlug, id; id = this.getID(); cellSlug = cell.data('slug'); this.prevHash = location.hash; return location.hash = "" + id + "-" + (this.getSlug()) + "/" + cellSlug; }; LightboxAdapter.prototype.resetHash = function() { if (this.prevHash) { location.hash = this.prevHash; delete this.prevHash; } else { location.hash = '#'; } if (this.scrollTop && this.scrollTop > 0) { return jQuery(document).scrollTop(this.scrollTop); } }; LightboxAdapter.prototype.onKeyUp = function(event) { if (event.keyCode === 37) { return this.onPrevSlide(); } else if (event.keyCode === 39) { return this.onNextSlide(); } else if (event.keyCode === 27) { return this.onAfterClose(); } }; LightboxAdapter.prototype.onAfterClose = function() { $(window).off('keyup', this.onKeyup); return this.resetHash(); }; LightboxAdapter.prototype.onNextSlide = function() { var lightboxLinks; this.currentIndex += 1; lightboxLinks = this.getLightboxLinks(); if (this.currentIndex === lightboxLinks.length) { this.currentIndex = lightboxLinks.length - 1; } return this.setHash(this.getLightboxLinks().eq(this.currentIndex).closest('.asg-image')); }; LightboxAdapter.prototype.onPrevSlide = function() { this.currentIndex -= 1; if (this.currentIndex < 0) { this.currentIndex = 0; } return this.setHash(this.getLightboxLinks().eq(this.currentIndex).closest('.asg-image')); }; return LightboxAdapter; })(); CustomAdapter = (function(_super) { __extends(CustomAdapter, _super); function CustomAdapter() { return CustomAdapter.__super__.constructor.apply(this, arguments); } return CustomAdapter; })(LightboxAdapter); FooBoxAdapter = (function(_super) { __extends(FooBoxAdapter, _super); function FooBoxAdapter() { this.addImages = __bind(this.addImages, this); this.initFoobox = __bind(this.initFoobox, this); this.fooboxPresent = __bind(this.fooboxPresent, this); this.reset = __bind(this.reset, this); return FooBoxAdapter.__super__.constructor.apply(this, arguments); } FooBoxAdapter.prototype.reset = function() { FooBoxAdapter.__super__.reset.call(this); if (this.fooboxPresent()) { return this.initFoobox(); } else { return $((function(_this) { return function() { if (_this.fooboxPresent()) { return _this.initFoobox(); } }; })(this)); } }; FooBoxAdapter.prototype.fooboxPresent = function() { return window.FOOBOX && window.FOOBOX.o; }; FooBoxAdapter.prototype.initFoobox = function() { var fooboxOptions; fooboxOptions = jQuery.extend({}, window.FOOBOX.o, { deeplinking: false, affiliate: false, slideshow: { enabled: true }, selector: this.linkSelector }); return this.$el.foobox(fooboxOptions).on('foobox.afterLoad', (function(_this) { return function(event) { return _this.setHash(_this.getLightboxLinks().eq(event.fb.item.index).closest('.asg-image')); }; })(this)).on('foobox.close', (function(_this) { return function() { return _this.resetHash(); }; })(this)); }; FooBoxAdapter.prototype.addImages = function(images) { var image, _i, _len; for (_i = 0, _len = images.length; _i < _len; _i++) { image = images[_i]; image = $(image).closest('.asg-image'); image.attr('title', this.getLightboxCaption1(image)); image.find('img').attr('alt', this.getLightboxCaption2(image)); } return FooBoxAdapter.__super__.addImages.call(this, images); }; return FooBoxAdapter; })(LightboxAdapter); JetpackAdapter = (function(_super) { __extends(JetpackAdapter, _super); function JetpackAdapter($el, config) { this.onPrevSlide = __bind(this.onPrevSlide, this); this.onNextSlide = __bind(this.onNextSlide, this); this.setHashFromCurrentIndex = __bind(this.setHashFromCurrentIndex, this); this.onAfterClose = __bind(this.onAfterClose, this); this.startCarousel = __bind(this.startCarousel, this); this.onImageClicked = __bind(this.onImageClicked, this); this.addImages = __bind(this.addImages, this); JetpackAdapter.__super__.constructor.call(this, $el, config); this.$el.data('carousel-extra', { blog_id: 1, permalink: 'http://awesome-gallery.dev' }); } JetpackAdapter.prototype.addImages = function(images) { var image, url, wrapper, _i, _len; images.addClass('tiled-gallery-item'); for (_i = 0, _len = images.length; _i < _len; _i++) { image = images[_i]; image = $(image); wrapper = image.closest('.asg-image'); url = image.find('.asg-image-wrapper').attr('href'); image.find('img').data({ 'orig-file': url, 'orig-size': "" + (wrapper.data('width')) + "," + (wrapper.data('height')), 'large-file': url, 'medium-file': url, 'small-file': url, 'image-title': this.getLightboxCaption1(wrapper), 'image-description': this.getLightboxCaption2(wrapper), 'image-meta': wrapper.data('meta'), 'attachment-id': wrapper.data('attachment-id') ? wrapper.data('attachment-id') : 'asg-hack', 'comments-opened': wrapper.data('attachment-id') ? 1 : null }); } return images.on('click', this.onImageClicked); }; JetpackAdapter.prototype.onImageClicked = function(event) { event.preventDefault(); if ($.fn.jp_carousel) { return this.startCarousel(event); } else { return $(document).ready(setTimeout(((function(_this) { return function() { return _this.startCarousel(event); }; })(this)), 500)); } }; JetpackAdapter.prototype.startCarousel = function(event) { this.currentIndex = this.$el.find(this.linkSelector).index($(event.target).closest('.asg-image-wrapper')); if (this.$el.jp_carousel) { this.$el.jp_carousel({ start_index: this.currentIndex, 'items_selector': ".asg-image:not(.asg-hidden) .asg-image-wrapper img" }); return setTimeout(this.setHashFromCurrentIndex, 500); } else { return $(document).ready((function(_this) { return function() { return setTimeout(function() { _this.$el.jp_carousel({ start_index: _this.currentIndex, 'items_selector': ".asg-image:not(.asg-hidden) .asg-image-wrapper img" }); return setTimeout(_this.setHashFromCurrentIndex, 500); }, 600); }; })(this)); } }; JetpackAdapter.prototype.onAfterClose = function() { JetpackAdapter.__super__.onAfterClose.apply(this, arguments); jQuery(document).off('keyup', this.onKeyUp); $('.jp-carousel-next-button').off('click', this.onNextSlide); return $('.jp-carousel-previous-button').off('click', this.onPrevSlide); }; JetpackAdapter.prototype.setHashFromCurrentIndex = function() { this.setHash(this.getLightboxLinks().eq(this.currentIndex).closest('.asg-image')); $('.jp-carousel-next-button').click(this.onNextSlide); $('.jp-carousel-previous-button').click(this.onPrevSlide); $(document).on('keyup', this.onKeyUp); return $(document).on('click', '.jp-carousel-close-hint', this.onAfterClose); }; JetpackAdapter.prototype.onNextSlide = function() { var lightboxLinks; this.currentIndex += 1; lightboxLinks = this.getLightboxLinks(); if (this.currentIndex === lightboxLinks.length) { this.currentIndex = 0; } return setTimeout(this.setHashFromCurrentIndex, 400); }; JetpackAdapter.prototype.onPrevSlide = function() { this.currentIndex -= 1; if (this.currentIndex < 0) { this.currentIndex = this.getLightboxLinks().size() - 1; } return setTimeout(this.setHashFromCurrentIndex, 400); }; return JetpackAdapter; })(LightboxAdapter); MagnificPopupAdapter = (function(_super) { __extends(MagnificPopupAdapter, _super); function MagnificPopupAdapter($el, config) { var _this; _this = this; $el.magnificPopup({ type: 'image', delegate: this.linkSelector, gallery: { enabled: true }, mainClass: 'mfp-asg', image: { titleSrc: function() { var caption_1, caption_2, el; el = this.currItem.el.parent(); if (caption_1 = el.find('.asg-lightbox-caption1').html()) { caption_1 = $('<h3 />').html(caption_1)[0].outerHTML; } else { caption_1 = ''; } if (caption_2 = el.find('.asg-lightbox-caption2').html()) { caption_2 = $('<div />').html(caption_2)[0].outerHTML; } else { caption_2 = ''; } if (caption_1 + caption_2) { return caption_1 + caption_2; } return null; }, markup: '<div class="mfp-figure">' + '<div class="mfp-close"></div>' + '<figure>' + '<div class="mfp-img"></div>' + '<div class="mfp-asg-border"></div>' + '<figcaption>' + '<div class="mfp-bottom-bar">' + '<div class="mfp-title"></div>' + '<div class="mfp-counter"></div>' + '</div>' + '</figcaption>' + '</figure>' + '</div>' }, callbacks: { open: (function() { jQuery('.mfp-wrap').addClass('mfp-asg'); return this._lastFocusedEl = null; }), markupParse: (function(template) { return template.find('.mfp-counter').remove(); }), afterClose: (function(_this) { return function() { return _this.resetHash(); }; })(this), afterChange: function() { return _this.setHash(this.currItem.el.closest('.asg-image')); } } }); MagnificPopupAdapter.__super__.constructor.call(this, $el, config); } return MagnificPopupAdapter; })(LightboxAdapter); SwipeboxAdapter = (function(_super) { __extends(SwipeboxAdapter, _super); function SwipeboxAdapter() { this.onImageClicked = __bind(this.onImageClicked, this); return SwipeboxAdapter.__super__.constructor.apply(this, arguments); } SwipeboxAdapter.prototype.onImageClicked = function(event) { var elements, lightboxImages; SwipeboxAdapter.__super__.onImageClicked.call(this, event); event.preventDefault(); elements = this.$el.find(this.linkSelector); lightboxImages = $.map(elements, (function(_this) { return function(image) { image = $(image); return { href: image.attr('href'), title: function() { var caption1, caption2, html; image = image.closest('.asg-image'); html = $('<div/>'); if (caption2 = _this.getLightboxCaption2(image)) { html.append($('<small class="asg-small"/>').html(caption2)); } if (caption1 = _this.getLightboxCaption1(image)) { html.append($('<div />').html(caption1)); } return html.html(); } }; }; })(this)); this.currentIndex = elements.index($(event.target).closest('a.asg-image-wrapper')); $.swipebox(lightboxImages, { initialIndexOnArray: this.currentIndex }); jQuery('#swipebox-next').click(this.onNextSlide); jQuery('#swipebox-prev').click(this.onPrevSlide); return jQuery(window).on('keyup', this.onKeyUp); }; return SwipeboxAdapter; })(LightboxAdapter); PrettyPhotoAdapter = (function(_super) { __extends(PrettyPhotoAdapter, _super); function PrettyPhotoAdapter() { this.onPrevSlide = __bind(this.onPrevSlide, this); this.onNextSlide = __bind(this.onNextSlide, this); this.onKeyUp = __bind(this.onKeyUp, this); this.onImageClicked = __bind(this.onImageClicked, this); return PrettyPhotoAdapter.__super__.constructor.apply(this, arguments); } PrettyPhotoAdapter.prototype.onImageClicked = function(event) { var descriptions, elements, titles, urls; event.preventDefault(); event.stopPropagation(); elements = this.$el.find(this.linkSelector); urls = elements.map((function(_this) { return function(index, image) { return $(image).closest('a.asg-image-wrapper').attr('href'); }; })(this)); titles = elements.map((function(_this) { return function(index, image) { return _this.getLightboxCaption1($(image).closest('.asg-image')); }; })(this)); descriptions = elements.map((function(_this) { return function(index, image) { return _this.getLightboxCaption2($(image).closest('.asg-image')); }; })(this)); $.fn.prettyPhoto(this.config.settings); $.prettyPhoto.open(urls, titles, descriptions, this.currentIndex = elements.index($(event.target).closest('.asg-image-wrapper'))); this.setHash($(event.target).closest('.asg-image')); $(document).on('keydown.prettyphoto', this.onKeyUp); $('.pp_previous').on('click.asg', this.onPrevSlide); return $('.pp_next').on('click.asg', this.onNextSlide); }; PrettyPhotoAdapter.prototype.onKeyUp = function(event) { if (event.keyCode === 37) { return this.onPrevSlide(); } else if (event.keyCode === 39) { return this.onNextSlide(); } else if (event.keyCode === 27) { return this.resetHash(); } }; PrettyPhotoAdapter.prototype.onNextSlide = function() { var lightboxLinks; this.currentIndex += 1; lightboxLinks = this.getLightboxLinks(); if (this.currentIndex === lightboxLinks.length) { this.currentIndex = lightboxLinks.length - 1; } return this.setHash(this.getLightboxLinks().eq(this.currentIndex).closest('.asg-image')); }; PrettyPhotoAdapter.prototype.onPrevSlide = function() { this.currentIndex -= 1; if (this.currentIndex < 0) { this.currentIndex = 0; } return this.setHash(this.getLightboxLinks().eq(this.currentIndex).closest('.asg-image')); }; return PrettyPhotoAdapter; })(LightboxAdapter); iLightboxAdapter = (function(_super) { __extends(iLightboxAdapter, _super); function iLightboxAdapter($el, config) { this.onImageClicked = __bind(this.onImageClicked, this); if (!$.iLightBox) { alert('iLightbox not detected. Please install end enable iLightbox plugin.'); } iLightboxAdapter.__super__.constructor.call(this, $el, config); } iLightboxAdapter.prototype.onImageClicked = function(event) { var elements, index, lightboxImages, options; iLightboxAdapter.__super__.onImageClicked.call(this, event); event.preventDefault(); elements = this.$el.find(this.linkSelector); lightboxImages = $.map(elements, (function(_this) { return function(el) { var data; data = $(el); return { title: _this.getLightboxCaption1(data), url: data.attr('href'), caption: _this.getLightboxCaption2(data), thumbnail: $(el).find('.asg-image-wrapper img').attr('src') }; }; })(this)); this.currentIndex = index = elements.index($(event.target).closest('.asg-image-wrapper')); options = $.extend(this.config.settings, ILIGHTBOX.options && eval("(" + rawurldecode(ILIGHTBOX.options) + ")") || {}); return $.iLightBox(lightboxImages, $.extend({ startFrom: index, callback: { onAfterChange: (function(_this) { return function(instance) { _this.currentIndex = instance.currentItem; return _this.setHash(elements.eq(_this.currentIndex).closest('.asg-image')); }; })(this), onHide: (function(_this) { return function() { return _this.resetHash(); }; })(this) } }, options)); }; return iLightboxAdapter; })(LightboxAdapter); GalleryFilters = (function() { function GalleryFilters($el, filterCallback) { this.onFilterClick = __bind(this.onFilterClick, this); this.createFilter = __bind(this.createFilter, this); this.createSortedFilters = __bind(this.createSortedFilters, this); this.createAll = __bind(this.createAll, this); this.add = __bind(this.add, this); var list; this.$el = $el; this.tags = []; this.filterCallback = filterCallback; this.current = null; this.$el.on('click', '.asg-filter', this.onFilterClick); this.$el.hide(); this.suspendCreation = false; if ((list = this.$el.data('list')) && list !== '') { this.add(list.split(/,\s*/)); this.suspendCreation = true; } } GalleryFilters.prototype.add = function(tags) { var tag, _i, _len; if (this.suspendCreation) { return; } for (_i = 0, _len = tags.length; _i < _len; _i++) { tag = tags[_i]; if (tag === '') { continue; } if (!this.tags.hasOwnProperty(tag)) { this.tags[tag] = true; if (!this.$el.data('sort')) { this.createFilter(tag); this.$el.show(); } } } if (this.$el.data('sort')) { this.$el.empty(); return this.createSortedFilters(); } else { if (this.tags.length !== 0) { return this.createAll(); } } }; GalleryFilters.prototype.createAll = function() { var all; this.$el.prepend(all = $("<div class='asg-filter' />").append($("<a data-tag='' href='#' />").text(this.$el.data('all')))); if (this.current === '' || this.current === null) { return all.addClass('asg-active'); } }; GalleryFilters.prototype.createSortedFilters = function() { var tag, tags, _i, _len; this.createAll(); tags = []; for (tag in this.tags) { if (this.tags.hasOwnProperty(tag)) { tags.push(tag); } } tags.sort(); for (_i = 0, _len = tags.length; _i < _len; _i++) { tag = tags[_i]; this.createFilter(tag); } if (tags.length > 0) { return this.$el.show(); } }; GalleryFilters.prototype.createFilter = function(tag) { var a, filter; filter = $('<div class="asg-filter" />').append(a = $("<a href='#' />").text(tag).attr('data-tag', tag)).appendTo(this.$el); if (tag === this.current) { return filter.addClass('asg-active'); } }; GalleryFilters.prototype.onFilterClick = function(event) { var filter; event.preventDefault(); filter = $(event.target); this.$el.find('> div').removeClass('asg-active'); $(filter).parent().addClass('asg-active'); this.current = $(filter).attr('data-tag'); return this.filterCallback(this.current); }; return GalleryFilters; })(); AwesomeGallery = (function() { var AnimationQueue, GalleryImage, GridLayoutStrategy, HorizontalFlowLayoutStrategy, ImageCaption, ImageOverlay, LayoutStrategy, SlidingElement, VerticalFlowLayoutStrategy; function AwesomeGallery(id, config) { this.dispose = __bind(this.dispose, this); this.applyFiltering = __bind(this.applyFiltering, this); this.getFilteredImages = __bind(this.getFilteredImages, this); this.add = __bind(this.add, this); this.loadMore = __bind(this.loadMore, this); this.initLoadMore = __bind(this.initLoadMore, this); this.loadMoreActive = __bind(this.loadMoreActive, this); this.deepLinkLoadMoreCallback = __bind(this.deepLinkLoadMoreCallback, this); this.showDeeplinkLoadOverlay = __bind(this.showDeeplinkLoadOverlay, this); this.showWhenVisible = __bind(this.showWhenVisible, this); var lightboxConfig; this.$window = $(window); this.id = id; this.config = config; this.page = 1; this.$el = $("#awesome-gallery-" + id); this.$el.data('awesome-gallery', this); this.$images = this.$el.find('.asg-images'); this.recursive = 0; this.animationQueue = new AnimationQueue(); if ((this.$filters = this.$el.find('.asg-filters')).size() > 0) { this.filters = new GalleryFilters(this.$filters, this.applyFiltering); } this.images = []; this.layout = LayoutStrategy.create(this.$images, this.config.layout, this.animationQueue); this.loading = false; this.loadMoreCount = 0; lightboxConfig = this.config.lightbox; if (this.loadMoreActive()) { lightboxConfig = $.extend({ loadMoreCallback: this.deepLinkLoadMoreCallback }, lightboxConfig); this.initLoadMore(); } this.lightboxAdapter = LightboxAdapter.create(this.$images, lightboxConfig); this.add(this.$el.find('.asg-image')); this.showWhenVisible(); } AwesomeGallery.prototype.showWhenVisible = function() { if (!this.$el.is(':visible') || this.$el.width() < 50) { return setTimeout(this.showWhenVisible, 250); } else { return this.layout.reLayout(); } }; AwesomeGallery.prototype.showDeeplinkLoadOverlay = function() { return this.$images.append('<div class="asg-deeplink-overlay"><div class="asg-deeplink-loader"></div></div>'); }; AwesomeGallery.prototype.deepLinkLoadMoreCallback = function() { this.loadMoreCount += 1; this.showDeeplinkLoadOverlay(); if (this.loadMoreCount < 3) { return this.loadMore((function(_this) { return function() { if (_this.lightboxAdapter.checkForDeeplink()) { return _this.$images.find('.asg-deeplink-overlay').remove(); } }; })(this)); } else { return this.$images.find('.asg-deeplink-overlay').remove(); } }; AwesomeGallery.prototype.loadMoreActive = function() { return this.$el.find('.asg-bottom').size() > 0; }; AwesomeGallery.prototype.initLoadMore = function() { if ((this.$loadMore = this.$el.find('.asg-bottom .asg-load-more')).size() > 0) { return this.$loadMore.click((function(_this) { return function() { _this.recursive = 0; return _this.loadMore(); }; })(this)); } else { return this.$window.on('scroll.asg', (function(_this) { return function() { if (!(_this.loading || _this.allLoaded)) { if (_this.$images.height() + _this.$images.offset().top - 400 < _this.$window.scrollTop() + _this.$window.height()) { return _this.loadMore(); } } }; })(this)); } }; AwesomeGallery.prototype.loadMore = function(callback) { if (this.loading || this.allLoaded) { return; } this.loading = true; if (this.$loadMore && this.$loadMore.size() > 0) { this.$loadMore.hide(); } this.$loading = this.$el.find('.asg-bottom .asg-loading').addClass('asg-visible'); return setTimeout((function(_this) { return function() { return $.post("" + _this.config.ajaxurl + "&page=" + (_this.page + 1) + "&id=" + _this.id, function(response) { var tmp; _this.loading = false; _this.page += 1; _this.$loading.removeClass('asg-visible'); if (response.have_more) { _this.$loadMore.show(); } else { _this.$el.find('.asg-bottom .asg-all-loaded').show(); _this.allLoaded = true; } tmp = $('<div/>').html(response.images); _this.add(tmp.find('.asg-image').appendTo(_this.$images)); if (callback) { return callback(); } }); }; })(this), 50); }; AwesomeGallery.prototype.add = function(images) { var image, newFilteredImages, newImage, newImages, _i, _len; newImages = []; for (_i = 0, _len = images.length; _i < _len; _i++) { image = images[_i]; newImage = new GalleryImage($(image), this.animationQueue, this.config); this.images.push(newImage); newImages.push(newImage); if (this.filters) { this.filters.add(newImage.getTags()); } } if (this.lightboxAdapter) { this.lightboxAdapter.addImages(images); } newFilteredImages = this.getFilteredImages(newImages); this.layout.add(newImages); this.layout.layout(newFilteredImages); if (newFilteredImages.length > 0) { } else { if (!this.loading && this.recursive < 2) { this.recursive += 1; return this.loadMore(); } } }; AwesomeGallery.prototype.getFilteredImages = function(images) { return images = $.grep(images, (function(_this) { return function(item) { var matches; matches = !_this.currentFilter || (jQuery.inArray(_this.currentFilter, item.getTags()) !== -1); if (matches) { item.show(); } else { item.hide(); } return matches; }; })(this)); }; AwesomeGallery.prototype.applyFiltering = function(filter) { this.currentFilter = filter; this.layout.reLayout(this.getFilteredImages(this.images)); if (this.lightboxAdapter) { this.lightboxAdapter.reset(); } return this.recursive = 0; }; AwesomeGallery.prototype.dispose = function() { this.$window.off('scroll', this.windowScrolled); if (this.$loadMore) { return this.$loadMore.off('click', this.loadNextPage); } }; SlidingElement = (function() { function SlidingElement($el, $wrapper, animationQueue) { this.slideOut = __bind(this.slideOut, this); this.cleanupClass = __bind(this.cleanupClass, this); this.slideIn = __bind(this.slideIn, this); this.getTransitionClass = __bind(this.getTransitionClass, this); this.$el = $el; this.$wrapper = $wrapper; this.animationQueue = animationQueue; if (transitionEndEvent) { this.$el.on(transitionEndEvent[transitionProp], this.cleanupClass); } else { setTimeout(((function(_this) { return function() { return _this.cleanupClass(); }; })(this)), 200); } if (!($el.hasClass('asg-position-bottom') && $el.hasClass('asg-effect-slide') && $el.hasClass('asg-on-hover'))) { if (!this.$el.hasClass('asg-off-hover')) { this.$wrapper.on('mouseout', this.cleanupClass); } if (this.$el.hasClass('asg-on-hover') && this.$el.hasClass('asg-effect-slide')) { this.$wrapper.hover(((function(_this) { return function(event) { return _this.slideIn(event); }; })(this)), (function(_this) { return function(event) { return _this.slideOut(event); }; })(this)); } } if (this.$el.hasClass('asg-off-hover') && this.$el.hasClass('asg-effect-slide')) { this.$wrapper.hover(((function(_this) { return function(event) { return _this.slideOut(event); }; })(this)), (function(_this) { return function(event) { return _this.slideIn(event); }; })(this)); } } SlidingElement.prototype.getTransitionClass = function(event) { var klass, x, y; x = event.offsetX - this.$wrapper.width() / 2; y = event.offsetY - this.$wrapper.height() / 2; if (x > 0) { if (Math.abs(x) > Math.abs(y)) { klass = 'asg-slide-right'; } else { if (y < 0) { klass = 'asg-slide-top'; } else { klass = 'asg-slide-bottom'; } } } else { if (Math.abs(x) > Math.abs(y)) { klass = 'asg-slide-left'; } else { if (y < 0) { klass = 'asg-slide-top'; } else { klass = 'asg-slide-bottom'; } } } return klass; }; SlidingElement.prototype.slideIn = function(event) { this.$el.addClass('asg-no-transition'); this.cleanupClass(); this.$el.addClass(this.getTransitionClass(event)); this.$el.height(); this.$el.removeClass('asg-no-transition'); return this.cleanupClass(); }; SlidingElement.prototype.cleanupClass = function() { var klass, _i, _len, _ref, _results; _ref = ['asg-slide-left', 'asg-slide-right', 'asg-slide-top', 'asg-slide-bottom']; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { klass = _ref[_i]; _results.push(this.$el.removeClass(klass)); } return _results; }; SlidingElement.prototype.slideOut = function(event) { var klass; klass = this.getTransitionClass(event); return this.$el.addClass(klass); }; return SlidingElement; })(); ImageOverlay = (function(_super) { __extends(ImageOverlay, _super); function ImageOverlay($el, $wrapper, animationQueue) { ImageOverlay.__super__.constructor.call(this, $el, $wrapper, animationQueue); } return ImageOverlay; })(SlidingElement); ImageCaption = (function(_super) { __extends(ImageCaption, _super); function ImageCaption($el, $wrapper, animationQueue) { this.layout = __bind(this.layout, this); var h, img; ImageCaption.__super__.constructor.call(this, $el, $wrapper, animationQueue); this.centered = $el.hasClass('asg-position-center'); if (this.centered) { $wrapper.hover(((function(_this) { return function() { return $el.css({ 'margin-top': -$el.outerHeight() / 2 }); }; })(this)), null); $el.on('resize', (function(_this) { return function() { return _this.layout(); }; })(this)); } img = $el.parent().find('img'); h = $el.height(); if ($el.hasClass('asg-position-bottom') && $el.hasClass('asg-effect-slide') && $el.hasClass('asg-on-hover')) { this.$wrapper.hover(((function(_this) { return function() { h = $el.outerHeight(); img.animate({ 'top': "-" + (h / 2) + "px" }, { 'queue': false, duration: 400 }); return $el.css({ bottom: "-" + h + "px" }).animate({ bottom: 0 }, { queue: false, duration: 350 }); }; })(this)), ((function(_this) { return function() { img.animate({ top: 0 }, { queue: false, duration: 400 }); return $el.animate({ bottom: "-" + h + "px" }, { queue: false, duration: 350 }); }; })(this))); } } ImageCaption.prototype.layout = function() { if (this.centered) { if (this.$el.hasClass('asg-mode-on') || this.$el.hasClass('asg-mode-on-hover')) { this.$el.css({ opacity: 0 }); } return setTimeout((function(_this) { return function() { var style; style = { 'margin-top': -_this.$el.outerHeight() / 2 }; if (_this.$el.hasClass('asg-mode-on') || _this.$el.hasClass('asg-mode-on-hover')) { _this.$el.css('opacity', ''); } return _this.$el.css(style); }; })(this), Math.random(500) + 600); } }; return ImageCaption; })(SlidingElement); AnimationQueue = (function() { function AnimationQueue() { this.flush = __bind(this.flush, this); this.clear = __bind(this.clear, this); this.enqueue = __bind(this.enqueue, this); } AnimationQueue.prototype.queue = []; AnimationQueue.prototype.queues = []; AnimationQueue.prototype.flushInterval = null; AnimationQueue.prototype.flushTimespan = 10; AnimationQueue.prototype.enqueue = function($el, style) { this.queue.push([$el, style]); if (!this.flushInterval) { return this.flushInterval = setTimeout(this.flush, this.flushTimespan); } }; AnimationQueue.prototype.clear = function() { this.queue = []; clearTimeout(this.flushInterval); return this.flushInterval = null; }; AnimationQueue.prototype.flush = function() { var i, item; i = 50; while (i > 0 && this.queue.length > 0) { item = this.queue.shift(); item[0].css(item[1]); i -= 1; } if (this.queue.length > 0) { this.flushInterval = setTimeout(this.flush, this.flushTimespan); return this.flushInterval = null; } }; return AnimationQueue; })(); GalleryImage = (function() { function GalleryImage($el, animationQueue, config) { this.slideIn = __bind(this.slideIn, this); this.layout = __bind(this.layout, this); this.getTags = __bind(this.getTags, this); this.show = __bind(this.show, this); this.hide = __bind(this.hide, this); var $caption, $overlay; this.$el = $el; this.animationQueue = animationQueue; this.$image = this.$el.find('.asg-image-wrapper img'); if (window.devicePixelRatio) { this.$image.attr('src', this.$image.attr('src') + ("&zoom=" + window.devicePixelRatio)); } if (this.$image[0].complete || this.$image[0].naturalWidth > 0) { this.$el.addClass('asg-loaded'); } else { this.$image.on('load', (function(_this) { return function() { return _this.$el.addClass('asg-loaded'); }; })(this)); } this.naturalWidth = this.$el.data('width'); this.naturalHeight = this.$el.data('height'); this.$el.data('asg-image', this); this.config = config; if (($overlay = this.$el.find('.asg-image-overlay')).size() > 0) { this.overlay = new ImageOverlay($overlay, this.$el, this.animationQueue); } if (($caption = this.$el.find('.asg-image-caption-wrapper')).size() > 0) { this.caption = new ImageCaption($caption, this.$el, this.animationQueue); } this.laidOut = false; this.$el.on('transitionend', (function(_this) { return function() { return setTimeout(function() { _this.$el.addClass('asg-laid-out'); return _this.laidOut = true; }, Math.random() * 1000 + 100); }; })(this)); } GalleryImage.prototype.hide = function() { return this.$el.addClass('asg-hidden'); }; GalleryImage.prototype.show = function() { return this.$el.removeClass('asg-hidden'); }; GalleryImage.prototype.getTags = function() { if (this.tags) { return this.tags; } return this.tags = this.$el.data('tags').split(', '); }; GalleryImage.prototype.layout = function(x, y, width, height) { var css; if (!this.laidOut) { setTimeout((function(_this) { return function() { _this.$el.addClass('asg-laid-out'); return _this.laidOut = true; }; })(this), Math.random() * 1000 + 100); } if (Modernizr.csstransforms && Modernizr.csstransitions) { css = { translate: [x, y] }; } else { css = { left: x, top: y }; } if (width && height) { this.animationQueue.enqueue(this.$el, $.extend(css, { width: width, height: height })); } else { this.animationQueue.enqueue(this.$el, css); } if (this.caption) { return this.caption.layout(); } }; GalleryImage.prototype.slideIn = function(event, element, zero) { var css, x, y; x = event.offsetX - this.wrapper.width() / 2; y = event.offsetY - this.wrapper.height() / 2; if (Math.abs(x) > Math.abs(y)) { if (x > 0) { css = { 'left': "" + (this.wrapper.width()) + "px", top: 0 }; } else { css = { 'left': "-" + (this.wrapper.width()) + "px", top: 0 }; } } else { if (y < 0) { css = { 'top': "-" + (this.wrapper.height()) + "px", left: 0 }; } else { css = { 'top': "" + (this.wrapper.height()) + "px", left: 0 }; } } return element.css(css).animate(zero, 'fast'); }; GalleryImage.prototype.slideOut = function(event, element) { var css, x, y; x = event.offsetX - this.wrapper.width() / 2; y = event.offsetY - this.wrapper.height() / 2; if (x > 0) { if (Math.abs(x) > Math.abs(y)) { css = { 'left': "" + (this.wrapper.width()) + "px" }; } else { if (y < 0) { css = { 'top': "-" + (this.wrapper.height()) + "px" }; } else { css = { 'top': "" + (this.wrapper.height()) + "px" }; } } } else { if (Math.abs(x) > Math.abs(y)) { css = { 'left': "-" + (this.wrapper.width()) + "px" }; } else { if (y < 0) { css = { 'top': "-" + (this.wrapper.height()) + "px" }; } else { css = { 'top': "" + (this.wrapper.height()) + "px" }; } } } return element.animate(css, 'fast'); }; return GalleryImage; })(); LayoutStrategy = (function() { LayoutStrategy.create = function(wrapper, config, animationQueue) { if (config.mode === "usual") { return new GridLayoutStrategy(wrapper, config, animationQueue); } else if (config.mode === "vertical-flow") { return new VerticalFlowLayoutStrategy(wrapper, config, animationQueue); } else if (config.mode === 'horizontal-flow') { return new HorizontalFlowLayoutStrategy(wrapper, config, animationQueue); } }; function LayoutStrategy($el, options, animationQueue) { this.getColumnWidth = __bind(this.getColumnWidth, this); this.getColumns = __bind(this.getColumns, this); this.reLayoutRequired = __bind(this.reLayoutRequired, this); this.layout = __bind(this.layout, this); this.add = __bind(this.add, this); this.reset = __bind(this.reset, this); this.reLayout = __bind(this.reLayout, this); this.onResized = __bind(this.onResized, this); this.$el = $el; this.images = []; this.animationQueue = animationQueue; $(window).smartresize(this.onResized); this.checkLayoutInterval = setInterval(this.onResized, 500); this.options = options; this.reset(); } LayoutStrategy.prototype.onResized = function() { if (this.reLayoutRequired()) { return this.reLayout(); } }; LayoutStrategy.prototype.reLayout = function(images) { if (images == null) { images = null; } if (images) { this.images = images; } this.reset(); return this.layout(); }; LayoutStrategy.prototype.reset = function() { this.index = 0; this.width = this.$el.parent().width(); this.columns = this.getColumns(); return this.columnWidth = this.getColumnWidth(); }; LayoutStrategy.prototype.add = function(images) { return this.images = this.images.concat(images); }; LayoutStrategy.prototype.layout = function(images) { var size; if (images == null) { images = null; } images = images || this.images; this.animationQueue.clear(); this.placeItems(images); size = this.getContainerSize(); return this.$el.css({ width: size.width + "px", height: size.height + "px" }); }; LayoutStrategy.prototype.reLayoutRequired = function() { return this.$el.parent().width() !== this.width; }; LayoutStrategy.prototype.getColumns = function() { var columns, fullWidth, width; width = this.width; columns = Math.floor((width + this.options.gap) / (this.options.width + this.options.gap + this.options.border * 2)); fullWidth = columns * (this.options.width + this.options.border * 2) + (columns - 1) * this.options.gap; if (width > fullWidth) { columns = columns + 1; } if (columns === 0) { columns = 1; } return columns; }; LayoutStrategy.prototype.getColumnWidth = function() { var columns; columns = this.columns; if (columns > 1) { return Math.floor((this.width + this.options.gap) / columns - this.options.gap); } return this.width; }; return LayoutStrategy; })(); GridLayoutStrategy = (function(_super) { __extends(GridLayoutStrategy, _super); function GridLayoutStrategy() { this.getContainerSize = __bind(this.getContainerSize, this); this.placeItems = __bind(this.placeItems, this); this.reset = __bind(this.reset, this); return GridLayoutStrategy.__super__.constructor.apply(this, arguments); } GridLayoutStrategy.prototype.reset = function() { GridLayoutStrategy.__super__.reset.apply(this, arguments); return this.rowHeight = Math.floor(this.options.height * this.columnWidth / this.options.width); }; GridLayoutStrategy.prototype.placeItems = function(images) { var border, col, image, row, x, y, _i, _len, _results; if (this.index === 0 && images.length < this.columns) { this.columns = images.length; this.columnWidth = this.options.width; this.rowHeight = this.options.height; } border = this.options.border * 2; _results = []; for (_i = 0, _len = images.length; _i < _len; _i++) { image = images[_i]; col = this.index % this.columns; row = Math.floor(this.index / this.columns); x = col * (this.columnWidth + this.options.gap); y = row * (this.rowHeight + this.options.gap); image.layout(x, y, this.columnWidth - border, Math.floor(this.rowHeight - border)); _results.push(this.index += 1); } return _results; }; GridLayoutStrategy.prototype.getContainerSize = function() { var size; size = {}; size.height = Math.ceil(1.0 * this.index / this.columns) * (this.rowHeight + this.options.gap + this.options.border); if (this.options.hanging === 'hide' && this.index % this.columns !== 0) { size.height -= this.rowHeight + this.options.gap + this.options.border; } if (this.index <= this.columns) { size.width = this.columnWidth * this.index + this.options.gap * this.index - 1; } else { size.width = this.width; } return size; }; return GridLayoutStrategy; })(LayoutStrategy); VerticalFlowLayoutStrategy = (function(_super) { __extends(VerticalFlowLayoutStrategy, _super); function VerticalFlowLayoutStrategy() { this.placeItems = __bind(this.placeItems, this); this.reset = __bind(this.reset, this); return VerticalFlowLayoutStrategy.__super__.constructor.apply(this, arguments); } VerticalFlowLayoutStrategy.prototype.reset = function() { var col, _i, _ref, _results; VerticalFlowLayoutStrategy.__super__.reset.apply(this, arguments); this.columnHeights = []; this.columnImages = []; _results = []; for (col = _i = 0, _ref = this.columns - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; col = 0 <= _ref ? ++_i : --_i) { this.columnImages[col] = []; _results.push(this.columnHeights[col] = 0); } return _results; }; VerticalFlowLayoutStrategy.prototype.placeItems = function(images) { var columnIndex, columnWidth, columns, highestColumn, highestHeight, image, imageHeight, imageWidth, lastInHighestColumn, lastInHighestColumnHeight, lowestColumn, lowestHeight, newLowestHeight, _i, _len; if (this.index === 0 && images.length < this.columns) { this.columns = images.length; this.columnWidth = this.options.width; } columns = this.columns; columnWidth = this.columnWidth; imageWidth = columnWidth - this.options.border * 2; for (_i = 0, _len = images.length; _i < _len; _i++) { image = images[_i]; imageHeight = image.naturalHeight * imageWidth * 1.0 / image.naturalWidth; columnIndex = this.index % columns; this.columnImages[columnIndex].push(image); image.layout(columnIndex * columnWidth + this.options.gap * columnIndex, this.columnHeights[columnIndex] + this.options.gap, imageWidth, imageHeight); this.columnHeights[columnIndex] += imageHeight + this.options.gap + this.options.border * 2; this.index += 1; } while (true) { lowestColumn = $.inArray(Math.min.apply(null, this.columnHeights), this.columnHeights); highestColumn = $.inArray(Math.max.apply(null, this.columnHeights), this.columnHeights); if (lowestColumn === highestColumn) { return; } lastInHighestColumn = this.columnImages[highestColumn].pop(); if (!lastInHighestColumn) { return; } lastInHighestColumnHeight = lastInHighestColumn.naturalHeight * imageWidth / lastInHighestColumn.naturalWidth + this.options.gap + this.options.border * 2; lowestHeight = this.columnHeights[lowestColumn]; highestHeight = this.columnHeights[highestColumn]; newLowestHeight = lowestHeight + lastInHighestColumnHeight; if (newLowestHeight >= highestHeight) { return; } this.columnImages[lowestColumn].push(lastInHighestColumn); lastInHighestColumn.layout(lowestColumn * (this.columnWidth + this.options.gap), this.columnHeights[lowestColumn] + this.options.gap); this.columnHeights[highestColumn] -= lastInHighestColumnHeight; this.columnHeights[lowestColumn] += lastInHighestColumnHeight; } }; VerticalFlowLayoutStrategy.prototype.getContainerSize = function() { var height, i, size, _i, _ref; height = 0; size = {}; for (i = _i = 0, _ref = this.columns - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; i = 0 <= _ref ? ++_i : --_i) { if (this.columnHeights[i] > height) { height = this.columnHeights[i]; } } if (this.index < this.columns) { size.width = this.columnWidth * this.index; } else { size.width = this.width; } size.height = height + this.options.gap; return size; }; return VerticalFlowLayoutStrategy; })(LayoutStrategy); HorizontalFlowLayoutStrategy = (function(_super) { __extends(HorizontalFlowLayoutStrategy, _super); function HorizontalFlowLayoutStrategy() { this.getContainerSize = __bind(this.getContainerSize, this); this.placeItems = __bind(this.placeItems, this); this.startNewRow = __bind(this.startNewRow, this); this.shrinkCurrentRow = __bind(this.shrinkCurrentRow, this); this.reset = __bind(this.reset, this); return HorizontalFlowLayoutStrategy.__super__.constructor.apply(this, arguments); } HorizontalFlowLayoutStrategy.prototype.reset = function() { HorizontalFlowLayoutStrategy.__super__.reset.apply(this, arguments); this.currentRow = []; this.sizes = []; this.currentRowWidth = 0; this.rows = [this.currentRow]; this.elementSizes = [this.sizes]; this.height = 0; return this.prevWidth = 0; }; HorizontalFlowLayoutStrategy.prototype.shrinkCurrentRow = function(newHeight) { var shrinkFactor, x; x = 0; shrinkFactor = this.options.height / newHeight; return $.each(this.currentRow, (function(_this) { return function(rowIndex, image) { var imageWidth; if (rowIndex !== _this.currentRow.length - 1 || _this.currentRowWidth < _this.prevWidth) { imageWidth = Math.floor(_this.sizes[rowIndex] / shrinkFactor); image.layout(x, _this.height, imageWidth, newHeight); return x += imageWidth + _this.options.gap + _this.options.border * 2; } else { return image.layout(x, _this.height, _this.width - x - _this.options.border * 2, newHeight); } }; })(this)); }; HorizontalFlowLayoutStrategy.prototype.startNewRow = function() { this.rows.push(this.currentRow = []); this.elementSizes.push(this.sizes = []); return this.currentRowWidth = 0; }; HorizontalFlowLayoutStrategy.prototype.placeItems = function(images) { var elementWidth, height, image, index, shrinkFactor, width, x, _i, _len; width = this.width; index = 0; for (_i = 0, _len = images.length; _i < _len; _i++) { image = images[_i]; this.currentRow.push(image); this.sizes.push(elementWidth = image.naturalWidth / image.naturalHeight * this.options.height); this.currentRowWidth += elementWidth + this.options.gap + this.options.border * 2; if (this.currentRowWidth >= width + this.options.gap) { this.currentRowWidth -= this.options.gap; shrinkFactor = (this.currentRowWidth - (this.currentRow.length - 1) * this.options.gap - this.currentRow.length * this.options.border * 2) / (width - (this.currentRow.length - 1) * this.options.gap - this.currentRow.length * this.options.border * 2); height = Math.floor(this.options.height / shrinkFactor); this.shrinkCurrentRow(height); this.height += height + this.options.gap + this.options.border * 2; this.startNewRow(); } index += 1; } if (this.currentRowWidth < this.width) { x = 0; return $.each(this.currentRow, (function(_this) { return function(rowIndex, image) { var imageWidth; imageWidth = Math.floor(_this.sizes[rowIndex]); image.layout(x, _this.height, imageWidth, _this.options.height); return x += imageWidth + _this.options.gap + _this.options.border * 2; }; })(this)); } }; HorizontalFlowLayoutStrategy.prototype.getContainerSize = function() { var size; size = {}; if (this.rows.length > 1) { size.height = this.height; if (this.options.allowHanging && this.currentRowWidth < this.width && this.currentRowWidth > 0) { size.height += this.options.height + this.options.gap + this.options.border * 2; } } else { if (this.currentRow.length > 0) { size.height = this.options.height + this.options.gap + this.options.border * 2; } else { size.height = 0; } } if (this.rows.length < 2 && this.currentRowWidth > 0) { size.width = this.currentRowWidth; } else { size.width = this.width; } return size; }; return HorizontalFlowLayoutStrategy; })(LayoutStrategy); return AwesomeGallery; })(); return window.AwesomeGallery = AwesomeGallery; } } })(window.asgjQuery || window.jQuery || window.$ || jQuery || $); }).call(this);
jcwproductions/jcwproductions-blog
wp-content/plugins/awesome-gallery/assets/js/awesome-gallery.js
JavaScript
gpl-2.0
76,673
import pathlib import h5py import numpy as np import pytest from scipy.ndimage.filters import gaussian_filter import dclab from dclab.rtdc_dataset.feat_anc_plugin.plugin_feature import ( PlugInFeature, import_plugin_feature_script, remove_plugin_feature, remove_all_plugin_features, PluginImportError) from dclab.rtdc_dataset.feat_anc_core.ancillary_feature import ( BadFeatureSizeWarning) from helper_methods import retrieve_data data_dir = pathlib.Path(__file__).parent / "data" @pytest.fixture(autouse=True) def cleanup_plugin_features(): """Fixture used to cleanup plugin feature tests""" # code run before the test pass # then the test is run yield # code run after the test # remove our test plugin examples remove_all_plugin_features() def compute_single_plugin_feature(rtdc_ds): """Basic plugin method""" circ_per_area = rtdc_ds["circ"] / rtdc_ds["area_um"] return circ_per_area def compute_multiple_plugin_features(rtdc_ds): """Basic plugin method with dictionary returned""" circ_per_area = rtdc_ds["circ"] / rtdc_ds["area_um"] circ_times_area = rtdc_ds["circ"] * rtdc_ds["area_um"] return {"circ_per_area": circ_per_area, "circ_times_area": circ_times_area} def compute_non_scalar_plugin_feature(rtdc_ds): """Basic non-scalar plugin method""" image_gauss_filter = gaussian_filter(rtdc_ds["image"], sigma=(0, 1, 1)) return {"image_gauss_filter": image_gauss_filter} def example_plugin_info_single_feature(): """plugin info for a single feature""" info = { "method": compute_single_plugin_feature, "description": "This plugin will compute a feature", "long description": "Even longer description that " "can span multiple lines", "feature names": ["circ_per_area"], "feature labels": ["Circularity per Area"], "features required": ["circ", "area_um"], "config required": [], "method check required": lambda x: True, "scalar feature": [True], "version": "0.1.0", } return info def example_plugin_info_multiple_feature(): """plugin info for multiple features""" info = { "method": compute_multiple_plugin_features, "description": "This plugin will compute some features", "long description": "Even longer description that " "can span multiple lines", "feature names": ["circ_per_area", "circ_times_area"], "feature labels": ["Circularity per Area", "Circularity times Area"], "features required": ["circ", "area_um"], "config required": [], "method check required": lambda x: True, "scalar feature": [True, True], "version": "0.1.0", } return info def example_plugin_info_non_scalar_feature(): """plugin info for non-scalar feature""" info = { "method": compute_non_scalar_plugin_feature, "description": "This plugin will compute a non-scalar feature", "long description": "This non-scalar feature is a Gaussian filter of " "the image", "feature names": ["image_gauss_filter"], "feature labels": ["Gaussian Filtered Image"], "features required": ["image"], "config required": [], "method check required": lambda x: True, "scalar feature": [False], "version": "0.1.0", } return info def compute_with_user_section(rtdc_ds): """setup a plugin method that uses user config section The "user:n_constrictions" metadata must be set """ nc = rtdc_ds.config["user"]["n_constrictions"] assert isinstance(nc, int), ( '"n_constrictions" should be an integer value.') area_of_region = rtdc_ds["area_um"] * nc return {"area_of_region": area_of_region} def test_pf_attribute_ancill_info(): """Check the plugin feature attribute input to AncillaryFeature""" info = example_plugin_info_single_feature() pf = PlugInFeature("circ_per_area", info) assert pf.plugin_feature_info["feature name"] == "circ_per_area" assert pf.plugin_feature_info["method"] is compute_single_plugin_feature assert pf.plugin_feature_info["config required"] == [] assert pf.plugin_feature_info["features required"] == ["circ", "area_um"] def test_pf_attribute_plugin_feature_info(): """Check the plugin feature info attribute""" info = example_plugin_info_single_feature() # comparing lambda functions fails due to differing memory locations info.pop("method check required") pf = PlugInFeature("circ_per_area", info) pf.plugin_feature_info.pop("method check required") plugin_feature_info = { "method": compute_single_plugin_feature, "description": "This plugin will compute a feature", "long description": "Even longer description that " "can span multiple lines", "feature name": "circ_per_area", "feature label": "Circularity per Area", "feature shape": (1,), "features required": ["circ", "area_um"], "config required": [], "scalar feature": True, "version": "0.1.0", "plugin path": None, "identifier": "3a3e72c4cb015424ebbe6d4af63f2170", } assert pf.plugin_feature_info == plugin_feature_info def test_pf_attributes(): """Check the plugin feature attributes""" plugin_path = data_dir / "feat_anc_plugin_creative.py" plugin_list = dclab.load_plugin_feature(plugin_path) pf1, pf2 = plugin_list plugin_file_info = import_plugin_feature_script(plugin_path) assert pf1.feature_name == pf1.feature_name == \ plugin_file_info["feature names"][0] assert pf2.feature_name == pf2.feature_name == \ plugin_file_info["feature names"][1] assert plugin_path.samefile(pf1.plugin_path) assert plugin_path.samefile(pf1.plugin_feature_info["plugin path"]) assert plugin_path.samefile(pf2.plugin_path) assert plugin_path.samefile(pf2.plugin_feature_info["plugin path"]) assert pf1._original_info == plugin_file_info assert pf2._original_info == plugin_file_info def test_pf_attributes_af_inherited(): """Check the plugin feature attributes inherited from AncillaryFeature""" plugin_path = data_dir / "feat_anc_plugin_creative.py" plugin_list = dclab.load_plugin_feature(plugin_path) pf, _ = plugin_list plugin_file_info = import_plugin_feature_script(plugin_path) assert pf.feature_name == plugin_file_info["feature names"][0] assert pf.method == plugin_file_info["method"] assert pf.req_config == plugin_file_info["config required"] assert pf.req_features == plugin_file_info["features required"] assert pf.req_func == plugin_file_info["method check required"] assert pf.priority == 0 def test_pf_bad_plugin_feature_name_list(): """Basic test of a bad feature name for PlugInFeature""" info = example_plugin_info_single_feature() info["feature names"] = "Peter-Pan's Best Friend!" with pytest.raises(ValueError, match="must be a list, got"): PlugInFeature("Peter-Pan's Best Friend!", info) def test_pf_bad_plugin_feature_name(): """Basic test of a bad feature name for PlugInFeature""" info = example_plugin_info_single_feature() info["feature names"] = ["Peter-Pan's Best Friend!"] with pytest.raises(ValueError, match="only contain lower-case characters"): PlugInFeature("Peter-Pan's Best Friend!", info) @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_exists_in_hierarchy(): """Test that RTDCHierarchy works with PlugInFeature""" info = example_plugin_info_single_feature() pf = PlugInFeature("circ_per_area", info) h5path = retrieve_data("fmt-hdf5_fl_2018.zip") with dclab.new_dataset(h5path) as ds: assert pf.feature_name in ds assert dclab.dfn.feature_exists(pf.feature_name) child = dclab.new_dataset(ds) assert pf.feature_name in child @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_export_and_load(): """Check that exported and loaded hdf5 file will keep a plugin feature""" h5path = retrieve_data("fmt-hdf5_fl_2018.zip") # initialize PlugInFeature instance info = example_plugin_info_single_feature() pf = PlugInFeature("circ_per_area", info) with dclab.new_dataset(h5path) as ds: # extract the feature information from the dataset assert pf in PlugInFeature.features circ_per_area = ds[pf.feature_name] # export the data to a new file expath = h5path.with_name("exported.rtdc") ds.export.hdf5(expath, features=ds.features_innate + [pf.feature_name]) # make sure that worked with h5py.File(expath, "r") as h5: assert pf.feature_name in h5["events"] assert np.allclose(h5["events"][pf.feature_name], circ_per_area) # now check again with dclab with dclab.new_dataset(expath) as ds2: assert pf in PlugInFeature.features assert pf.feature_name in ds2 assert pf.feature_name in ds2.features_innate assert np.allclose(ds2[pf.feature_name], circ_per_area) # and a control check remove_plugin_feature(pf) assert pf.feature_name not in ds2 @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_export_non_scalar(): h5path = retrieve_data("fmt-hdf5_image-bg_2020.zip") # initialize PlugInFeature instance info = example_plugin_info_non_scalar_feature() pf = PlugInFeature("image_gauss_filter", info) with dclab.new_dataset(h5path) as ds: # extract the feature information from the dataset assert pf in PlugInFeature.features image_gauss_filter = ds[pf.feature_name] # export the data to a new file expath = h5path.with_name("exported.rtdc") with pytest.warns(UserWarning, match="out on a limb"): ds.export.hdf5(expath, features=[pf.feature_name]) # make sure that worked with h5py.File(expath, "r") as h5: assert pf.feature_name in h5["events"] assert np.allclose(h5["events"][pf.feature_name], image_gauss_filter) @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_export_non_scalar_single_event(): h5path = retrieve_data("fmt-hdf5_image-bg_2020.zip") # initialize PlugInFeature instance info = example_plugin_info_non_scalar_feature() info["feature shapes"] = [(80, 250)] pf = PlugInFeature("image_gauss_filter", info) with dclab.new_dataset(h5path) as ds: # extract the feature information from the dataset assert pf in PlugInFeature.features image_gauss_filter = ds[pf.feature_name] # export the data to a new file expath = h5path.with_name("exported.rtdc") ds.export.hdf5(expath, features=["image", pf.feature_name]) # write another single event with dclab.RTDCWriter(expath) as hw: hw.store_feature(pf.feature_name, ds["image"][0]) hw.store_feature("image", ds["image"][0]) # make sure that worked with h5py.File(expath, "r") as h5: assert pf.feature_name in h5["events"] assert np.allclose(h5["events"][pf.feature_name][:-1], image_gauss_filter) assert np.allclose(h5["events"][pf.feature_name][-1], h5["events/image"][0]) @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_export_non_scalar_no_warning(): h5path = retrieve_data("fmt-hdf5_image-bg_2020.zip") # initialize PlugInFeature instance info = example_plugin_info_non_scalar_feature() info["feature shapes"] = [(80, 250)] pf = PlugInFeature("image_gauss_filter", info) with dclab.new_dataset(h5path) as ds: # extract the feature information from the dataset assert pf in PlugInFeature.features image_gauss_filter = ds[pf.feature_name] # export the data to a new file expath = h5path.with_name("exported.rtdc") ds.export.hdf5(expath, features=[pf.feature_name]) # make sure that worked with h5py.File(expath, "r") as h5: assert pf.feature_name in h5["events"] assert np.allclose(h5["events"][pf.feature_name], image_gauss_filter) @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_export_non_scalar_bad_shape(): h5path = retrieve_data("fmt-hdf5_image-bg_2020.zip") # initialize PlugInFeature instance info = example_plugin_info_non_scalar_feature() info["feature shapes"] = [(42, 27)] pf = PlugInFeature("image_gauss_filter", info) with dclab.new_dataset(h5path) as ds: # extract the feature information from the dataset assert pf in PlugInFeature.features # export the data to a new file expath = h5path.with_name("exported.rtdc") with pytest.raises(ValueError, match="Bad shape"): ds.export.hdf5(expath, features=[pf.feature_name]) def test_pf_feature_exists(): """Basic check that the plugin feature name exists in definitions""" plugin_path = data_dir / "feat_anc_plugin_creative.py" plugin_list = dclab.load_plugin_feature(plugin_path) assert dclab.dfn.feature_exists(plugin_list[0].feature_name) assert dclab.dfn.feature_exists(plugin_list[1].feature_name) @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_filtering_with_plugin_feature(): """Filtering with plugin feature""" h5path = retrieve_data("fmt-hdf5_fl_2018.zip") with dclab.new_dataset(h5path) as ds: info = example_plugin_info_single_feature() pf = PlugInFeature("circ_per_area", info) ds.config["filtering"][f"{pf.feature_name} min"] = 0.030 ds.config["filtering"][f"{pf.feature_name} max"] = 0.031 ds.apply_filter() assert np.sum(ds.filter.all) == 1 assert ds.filter.all[4] def test_pf_import_plugin_info(): """Check the plugin test example info is a dict""" plugin_path = data_dir / "feat_anc_plugin_creative.py" info = import_plugin_feature_script(plugin_path) assert isinstance(info, dict) def test_pf_import_plugin_info_bad_path(): """Raise error when a bad pathname is given""" bad_plugin_path = "not/a/real/path/plugin.py" with pytest.raises(PluginImportError, match="could be not be found"): import_plugin_feature_script(bad_plugin_path) def test_pf_incorrect_input_info(): """Raise error when info is not a dictionary""" info = ["this", "is", "not", "a", "dict"] with pytest.raises(ValueError, match="must be a dict"): PlugInFeature("feature_1", info) def test_pf_incorrect_input_feature_name(): """Raise error when the feature_name doesn't match info feature name""" info = example_plugin_info_single_feature() # `feature_name` is "circ_per_area" in info with pytest.raises(ValueError, match="is not defined"): PlugInFeature("not_the_correct_name", info) def test_pf_incorrect_input_method(): """Raise error when method is not callable""" info = example_plugin_info_single_feature() # set `info["method"]` to something that isn't callable info["method"] = "this_is_a_string" with pytest.raises(ValueError, match="is not callable"): PlugInFeature("circ_per_area", info) @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_initialize_plugin_after_loading(): """plugin feature loads correctly after feature added to hdf5 file""" h5path = retrieve_data("fmt-hdf5_fl_2018.zip") with dclab.new_dataset(h5path) as ds: circ_per_area = compute_single_plugin_feature(ds) with h5py.File(h5path, "a") as h5: h5["events"]["circ_per_area"] = circ_per_area with dclab.new_dataset(h5path) as ds: assert "circ_per_area" not in ds info = example_plugin_info_single_feature() PlugInFeature("circ_per_area", info) assert "circ_per_area" in ds assert "circ_per_area" in ds.features_innate @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_initialize_plugin_feature_single(): """Check that single plugin feature exists independant of loaded dataset""" ds = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip")) info = example_plugin_info_single_feature() PlugInFeature("circ_per_area", info) assert "circ_per_area" in ds circ_per_area = ds["circ_per_area"] assert np.allclose(circ_per_area, ds["circ"] / ds["area_um"]) # check that PlugInFeature exists independent of loaded ds ds2 = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip")) assert "circ_per_area" in ds2 @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_initialize_plugin_feature_non_scalar(): """Check that the non-scalar plugin feature works""" ds = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip")) info = example_plugin_info_non_scalar_feature() PlugInFeature("image_gauss_filter", info) assert "image_gauss_filter" in ds image_gauss_filter = ds["image_gauss_filter"] assert np.allclose(image_gauss_filter, gaussian_filter(ds["image"], sigma=(0, 1, 1))) @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_initialize_plugin_features_multiple(): """Check multiple plugin features exist independant of loaded dataset""" ds = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip")) assert "circ_per_area" not in ds.features_innate assert "circ_times_area" not in ds.features_innate info = example_plugin_info_multiple_feature() PlugInFeature("circ_per_area", info) PlugInFeature("circ_times_area", info) assert "circ_per_area" in ds assert "circ_times_area" in ds assert dclab.dfn.feature_exists("circ_per_area") assert dclab.dfn.feature_exists("circ_times_area") circ_per_area = ds["circ_per_area"] circ_times_area = ds["circ_times_area"] assert np.allclose(circ_per_area, ds["circ"] / ds["area_um"]) assert np.allclose(circ_times_area, ds["circ"] * ds["area_um"]) def test_pf_input_no_feature_labels(): """Check that feature labels are populated even if not given""" info = example_plugin_info_single_feature() info.pop("feature labels") feature_name = "circ_per_area" pf = PlugInFeature(feature_name, info) assert dclab.dfn.feature_exists(feature_name) label = dclab.dfn.get_feature_label(feature_name) assert label == "Plugin feature {}".format(feature_name) assert label == pf.plugin_feature_info["feature label"] def test_pf_input_no_scalar_feature(): """Check that scalar feature bools are populated even if not given""" info = example_plugin_info_single_feature() info.pop("scalar feature") pf = PlugInFeature("circ_per_area", info) assert pf.plugin_feature_info["scalar feature"] @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_load_plugin(): """Basic check for loading a plugin feature via a script""" ds = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip")) assert "circ_per_area" not in ds.features_innate assert "circ_times_area" not in ds.features_innate plugin_path = data_dir / "feat_anc_plugin_creative.py" plugin_list = dclab.load_plugin_feature(plugin_path) assert isinstance(plugin_list[0], PlugInFeature) assert isinstance(plugin_list[1], PlugInFeature) assert "circ_per_area" in ds assert "circ_times_area" in ds circ_per_area = ds["circ_per_area"] circ_times_area = ds["circ_times_area"] assert np.allclose(circ_per_area, ds["circ"] / ds["area_um"]) assert np.allclose(circ_times_area, ds["circ"] * ds["area_um"]) def test_pf_minimum_info_input(): """Only method and feature names are required to create PlugInFeature""" info = {"method": compute_single_plugin_feature, "feature names": ["circ_per_area"]} pf = PlugInFeature("circ_per_area", info) # check that all other plugin_feature_info is populated assert "method" in pf.plugin_feature_info assert callable(pf.plugin_feature_info["method"]) assert "description" in pf.plugin_feature_info assert "long description" in pf.plugin_feature_info assert "feature name" in pf.plugin_feature_info assert "feature label" in pf.plugin_feature_info assert "features required" in pf.plugin_feature_info assert "config required" in pf.plugin_feature_info assert "method check required" in pf.plugin_feature_info assert "scalar feature" in pf.plugin_feature_info assert "version" in pf.plugin_feature_info assert "plugin path" in pf.plugin_feature_info @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_remove_all_plugin_features(): """Remove all plugin features at once""" ds = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip")) assert "circ_per_area" not in ds.features_innate assert "circ_times_area" not in ds.features_innate plugin_path = data_dir / "feat_anc_plugin_creative.py" dclab.load_plugin_feature(plugin_path) assert "circ_per_area" in ds assert "circ_times_area" in ds assert dclab.dfn.feature_exists("circ_per_area") assert dclab.dfn.feature_exists("circ_times_area") remove_all_plugin_features() assert "circ_per_area" not in ds assert "circ_times_area" not in ds assert not dclab.dfn.feature_exists("circ_per_area") assert not dclab.dfn.feature_exists("circ_times_area") @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_remove_plugin_feature(): """Remove individual plugin features""" ds = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip")) assert "circ_per_area" not in ds assert "circ_times_area" not in ds plugin_path = data_dir / "feat_anc_plugin_creative.py" plugin_list = dclab.load_plugin_feature(plugin_path) assert len(plugin_list) == 2 assert "circ_per_area" in ds assert "circ_per_area" not in ds.features_innate assert "circ_times_area" in ds assert "circ_times_area" not in ds.features_innate assert dclab.dfn.feature_exists("circ_per_area") assert dclab.dfn.feature_exists("circ_times_area") remove_plugin_feature(plugin_list[0]) remove_plugin_feature(plugin_list[1]) assert "circ_per_area" not in ds assert "circ_times_area" not in ds assert not dclab.dfn.feature_exists("circ_per_area") assert not dclab.dfn.feature_exists("circ_times_area") with pytest.raises(TypeError, match="hould be an instance of PlugInFeature"): not_a_plugin_instance = [4, 6, 5] remove_plugin_feature(not_a_plugin_instance) def test_pf_try_existing_feature_fails(): """An existing feature name is not allowed""" info = example_plugin_info_single_feature() info["feature names"] = ["deform"] with pytest.raises(ValueError, match="Feature 'deform' already exists"): PlugInFeature("deform", info) def test_pf_with_empty_feature_label_string(): """An empty string is replaced with a real feature label Show that an empty `feature_label` will still give a descriptive feature label. See `dclab.dfn._add_feature_to_definitions` for details. """ info = example_plugin_info_single_feature() info["feature labels"] = [""] feature_name = "circ_per_area" PlugInFeature(feature_name, info) assert dclab.dfn.feature_exists("circ_per_area") label = dclab.dfn.get_feature_label("circ_per_area") assert label != "" assert label == "Plugin feature {}".format(feature_name) def test_pf_with_feature_label(): """Check that a plugin feature label is added to definitions""" info = example_plugin_info_single_feature() info["feature labels"] = ["Circ / Area [1/µm²]"] feature_name = "circ_per_area" PlugInFeature(feature_name, info) assert dclab.dfn.feature_exists("circ_per_area") label = dclab.dfn.get_feature_label("circ_per_area") assert label == "Circ / Area [1/µm²]" def test_pf_with_no_feature_label(): """A feature label of None is replaced with a real feature label Show that `feature_label=None` will still give a descriptive feature label. See `dclab.dfn._add_feature_to_definitions` for details. """ info = example_plugin_info_single_feature() info["feature labels"] = [None] feature_name = "circ_per_area" PlugInFeature(feature_name, info) assert dclab.dfn.feature_exists("circ_per_area") label = dclab.dfn.get_feature_label("circ_per_area") assert label is not None assert label == "Plugin feature {}".format(feature_name) @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_with_user_config_section(): """Use a plugin feature with the user defined config section""" info = {"method": compute_with_user_section, "feature names": ["area_of_region"], "config required": [["user", ["n_constrictions"]]]} PlugInFeature("area_of_region", info) ds = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip")) assert "area_of_region" not in ds, "not available b/c missing metadata" # add some metadata to the user config section metadata = {"channel": True, "n_constrictions": 3} ds.config["user"].update(metadata) assert ds.config["user"] == metadata assert "area_of_region" in ds, "available b/c metadata is set" area_of_region1 = ds["area_of_region"] area_of_region1_calc = (ds["area_um"] * ds.config["user"]["n_constrictions"]) assert np.allclose(area_of_region1, area_of_region1_calc) @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_with_user_config_section_fails(): """Use a plugin feature with the user defined config section""" info = {"method": compute_with_user_section, "feature names": ["area_of_region"], "config required": [["user", ["n_constrictions"]]]} PlugInFeature("area_of_region", info) ds = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip")) # show that the plugin feature is not available before setting the # user metadata ds.config["user"].clear() with pytest.raises(KeyError, match=r"Feature \'area_of_region\' does not exist"): ds["area_of_region"] # show that the plugin fails when the user metadata type is wrong ds.config["user"]["n_constrictions"] = 4.99 with pytest.raises(AssertionError, match="should be an integer value"): ds["area_of_region"] @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_wrong_data_shape_1(): h5path = retrieve_data("fmt-hdf5_fl_2018.zip") with dclab.new_dataset(h5path) as ds: info = example_plugin_info_single_feature() info["scalar feature"] = [False] pf = PlugInFeature("circ_per_area", info) with pytest.raises(ValueError, match="is not a scalar feature"): ds[pf.feature_name] @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_wrong_data_shape_2(): h5path = retrieve_data("fmt-hdf5_fl_2018.zip") with dclab.new_dataset(h5path) as ds: info = example_plugin_info_single_feature() info["scalar feature"] = [True] info["method"] = lambda x: np.arange(len(ds) * 2).reshape(-1, 2) pf = PlugInFeature("circ_per_area", info) with pytest.raises(ValueError, match="is a scalar feature"): ds[pf.feature_name] @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_wrong_length_1(): """plugin feature should have same length""" h5path = retrieve_data("fmt-hdf5_fl_2018.zip") with dclab.new_dataset(h5path) as ds: info = example_plugin_info_single_feature() info["method"] = lambda x: np.arange(len(ds) // 2) pf = PlugInFeature("circ_per_area", info) with pytest.warns(BadFeatureSizeWarning, match="to match event number"): ds[pf.feature_name] @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_wrong_length_2(): """plugin feature should have same length""" h5path = retrieve_data("fmt-hdf5_fl_2018.zip") with dclab.new_dataset(h5path) as ds: info = example_plugin_info_single_feature() info["method"] = lambda x: np.arange(len(ds) * 2) pf = PlugInFeature("circ_per_area", info) with pytest.warns(BadFeatureSizeWarning, match="to match event number"): ds[pf.feature_name] if __name__ == "__main__": # Run all tests loc = locals() for key in list(loc.keys()): if key.startswith("test_") and hasattr(loc[key], "__call__"): loc[key]() remove_all_plugin_features()
ZellMechanik-Dresden/dclab
tests/test_rtdc_feat_anc_plugin.py
Python
gpl-2.0
29,760
package net.idtoki.instelec.controller; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.ResourceBundle; import java.util.logging.Logger; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamSource; import org.apache.torque.TorqueException; import org.apache.torque.util.Criteria; import net.idtoki.instelec.manager.TareasManager; import net.idtoki.instelec.group.TareasGroupBean; import net.idtoki.instelec.helper.TareasHelper; import net.idtoki.instelec.model.TareasPeer; import net.idtoki.instelec.model.Tareas; import net.idtoki.instelec.manager.OrdenestrabajoManager; import net.idtoki.instelec.group.OrdenestrabajoGroupBean; import net.idtoki.instelec.model.OrdenestrabajoPeer; import net.idtoki.instelec.helper.OrdenestrabajoHelper; import net.idtoki.instelec.manager.TipotareasManager; import net.idtoki.instelec.group.TipotareasGroupBean; import net.idtoki.instelec.model.TipotareasPeer; import net.idtoki.instelec.helper.TipotareasHelper; import net.idtoki.instelec.manager.CategoriasManager; import net.idtoki.instelec.group.CategoriasGroupBean; import net.idtoki.instelec.model.CategoriasPeer; import net.idtoki.instelec.helper.CategoriasHelper; import net.idtoki.instelec.helper.MaterialesHelper; import net.zylk.tools.ajax.AjaxUtils; import net.zylk.tools.ajax.AjaxUtils.DinamicGridBean; import net.zylk.tools.format.FormatUtils; import net.zylk.tools.pdf.PdfUtils; import net.zylk.tools.xml.XmlUtils; import net.zylk.torque.TorqueUtils; import net.zylk.web.WebUtils; /** * The skeleton for this class was autogenerated by Torque on: * * [Thu Aug 10 13:35:35 CEST 2006] * * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. */ public class TareasController extends net.idtoki.instelec.controller.BaseTareasController { private static final Logger logger = Logger.getLogger("net.idtoki.instelec.controller.TareasController"); private TransformerFactory tFactory = TransformerFactory.newInstance(); private Transformer tareas_transformer = null; private Transformer tareass_transformer = null; public void init(ServletConfig config) { super.init(); ResourceBundle resource = ResourceBundle.getBundle("net/idtoki/instelec/app/config/app-config"); File tareas = new File(resource.getString("app.xsl.templates.dir")+"/PdfTareas.xslt"); Source xslSource = new StreamSource(tareas); File tareass = new File(resource.getString("app.xsl.templates.dir")+"/PdfListaTareas.xslt"); Source xslSourceT = new StreamSource(tareass); try{ tareas_transformer = tFactory.newTransformer(xslSource); tareass_transformer = tFactory.newTransformer(xslSourceT); }catch (Exception e){ e.printStackTrace(); } } //Función para la inserción/actualización de registros public void serviceAddTareas(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { //Con esto se consigue transformar el request a UTF //para temas de acentos y otros caracteres utf8RequestService(request); //recojo los parametros del formulario y doy de alta un nuevo elmento try { Tareas elTareas = TareasHelper.createObj(request); TareasGroupBean gbTareas = new TareasGroupBean(); elTareas.setFechainicio(FormatUtils.ddmmaaaa2aaaammdd(elTareas.getFechainicio(),"-","")); gbTareas.setElemento(elTareas); gbTareas.save(); } catch(TorqueException te) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } //Función para la eliminación de un registro //este método invoca al método public void deleteTareas(int idBorrar) //definido en el TareasManager public void serviceDeleteTareas(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { int idBorrar=-1; idBorrar=WebUtils.getintParam(request, "borrarId"); if (idBorrar!=-1) if (TareasManager.borraTareas(idBorrar)) WebUtils.writeXmlResponse(response,XmlUtils.buildXmlOKResponse("ISO-8859-1")); else WebUtils.writeXmlResponse(response,XmlUtils.buildXmlNotOKResponse("ISO-8859-1")); } // Funciones para las ordenaciones y filtrados de información private Criteria ordenacion(Criteria c,String CampoOrdenacion,String OrdenOrdenacion) { if((OrdenOrdenacion != null )&& (OrdenOrdenacion.compareTo("ASC")==0)) if ((CampoOrdenacion != null)) { c.addAscendingOrderByColumn(CampoOrdenacion.toString()); } if ((OrdenOrdenacion != null) && (OrdenOrdenacion.compareTo("DESC")==0)) if ((CampoOrdenacion != null)) { c.addDescendingOrderByColumn(CampoOrdenacion.toString()); } return c; } private Criteria filtro(Criteria c,int filtro) { String cadena = null; switch (filtro) { case 1: //Caso uno de Filtrado //c.add(Campo,valor); break; case 2: //Caso dos de Filtrado //c.add(Campo,valor); break; default: //caso por defecto break; } return c; } public StringBuffer replaceStringBuffer (StringBuffer strBA, String strOrigen, String strDestino) { return new StringBuffer(strBA.toString().replaceAll(strOrigen,strDestino)); } private Criteria criteriaTareasTableContent(HttpServletRequest request,Criteria c) throws IOException, ServletException { String param = ""; param = WebUtils.getStringParam(request, new OrdenestrabajoHelper().getIdordenName()); if(param != null) TorqueUtils.addEqualCriteria(c,TareasPeer.IDORDEN,param); param = WebUtils.getStringParam(request, new TipotareasHelper().getIdtipotareaName()); if(param != null) TorqueUtils.addEqualCriteria(c,TareasPeer.IDTIPOTAREA,param); param = WebUtils.getStringParam(request, new CategoriasHelper().getIdcategoriaName()); if(param != null) TorqueUtils.addEqualCriteria(c,TareasPeer.IDCATEGORIA,param); String paramSortCol = WebUtils.getStringParam(request, "sort_col"); String paramSortDir = WebUtils.getStringParam(request, "sort_dir"); int paramFiltro = WebUtils.getintParam(request, "filtro"); c = ordenacion(c,paramSortCol,paramSortDir); c = filtro(c,paramFiltro); return c; } public String getPathElementTareas(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, TorqueException { Criteria c= new Criteria(); String strPath = ""; int claveId=-1; int claveFkId=-1; claveId=WebUtils.getintParam(request, "tareas.IDTAREA"); if (claveId!=-1) { c.add(TareasPeer.IDTAREA, claveId); TareasGroupBean trgb = TareasManager.getTareass(c); strPath = trgb.getTareas(0).getPathTareasParsed(request.getQueryString()); } return "<path>" + strPath + "</path>"; } public String getPathTableContentTareas(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, TorqueException { Criteria c= new Criteria(); String strPath = ""; int claveId=-1; claveId=WebUtils.getintParam(request, "ordenestrabajo.IDORDEN"); if(claveId != -1){ strPath = OrdenestrabajoManager.getOrdenestrabajo(claveId).getPathOrdenestrabajoParsed(request.getQueryString()); } claveId=WebUtils.getintParam(request, "tipotareas.IDTIPOTAREA"); if(claveId != -1){ strPath = TipotareasManager.getTipotareas(claveId).getPathTipotareasParsed(request.getQueryString()); } claveId=WebUtils.getintParam(request, "categorias.IDCATEGORIA"); if(claveId != -1){ strPath = CategoriasManager.getCategorias(claveId).getPathCategoriasParsed(request.getQueryString()); } return "<path>" + strPath + "</path>"; } public void serviceTareasTableContent(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, TorqueException { utf8RequestService(request); int numElemPedidosBD = 40; int gap = 0;//gap = viewedRows - numElemVisiblesUltPag DinamicGridBean dgb = WebUtils.getDinamicGridBeanParam(request,numElemPedidosBD,gap); Criteria c =TareasManager.buildSearchCriteria(dgb); c =criteriaTareasTableContent(request,c); TareasGroupBean cgb = TareasManager.getTareass(c); dgb.setTotalSize(cgb.getTotalSize()); String[] methodos= new String[] { TareasHelper.FECHAINICIO_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.HORAS_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.IDORDEN_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.IDTIPOTAREA_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.IDCATEGORIA_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.OBSERVACIONES_GET_METHOD_NAME+"TareasParsed" ,"getHijosMaterialesTareas" ,"getEditTareas" ,"getDeleteTareas" }; StringBuffer cadena=null; cadena = AjaxUtils.buildXmlAjaxResponseTableContentFromListObj(cgb.getAlmacen(),methodos,TareasHelper.IDTAREA_GET_METHOD_NAME, dgb,"ISO-8859-1"); cadena.insert(cadena.indexOf("</ajax-response>"),"<response type='object' id='divPath'>" + getPathTableContentTareas(request,response) + "</response>"); xmlResponseService(response,cadena); } public void serviceTareasUlContent(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { utf8RequestService(request); String[] methodos= new String[] { "getULContentTareasParsed" }; String param = WebUtils.getStringParam(request, "value"); if(param==null || param.length() <= 0) param = WebUtils.getStringParam(request, new MaterialesHelper().getIdtareaName()); TareasGroupBean mgb = TareasManager.getTareass(TareasManager.buildSearchCriteria(param)); simpleResponseService(response, AjaxUtils.buildAjaxULContentFromListObj(mgb.getAlmacen(),methodos, TareasHelper.COMPLEX_ID_GET_METHOD,"Tareas")); } public void serviceTareasElement(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, TorqueException { StringBuffer cadena=null; Criteria c= new Criteria(); int claveId=-1; claveId=WebUtils.getintParam(request, "tareas.IDTAREA"); if (claveId!=-1) { c.add(TareasPeer.IDTAREA, claveId); } c.addAscendingOrderByColumn(TareasPeer.IDTAREA); TareasGroupBean trgb = TareasManager.getTareass(c); if (trgb.getTotalSize()!=0) { String [] parametros={ TareasHelper.IDTAREA_GET_METHOD_NAME ,TareasHelper.FECHAINICIO_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.HORAS_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.IDORDEN_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.IDTIPOTAREA_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.IDCATEGORIA_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.OBSERVACIONES_GET_METHOD_NAME+"TareasParsed" ,"getImporteCalculadoTareasParsed" ,"getManoObraCalculadoTareasParsed" }; cadena=trgb.buildXml(parametros,null,"ISO-8859-1"); cadena.insert(cadena.indexOf("</result>"),getPathElementTareas(request,response)); } xmlResponseService(response, cadena); } protected StringBuffer updateIdtareaResponseCallBack(String s) { ArrayList a = AjaxUtils.splitIdFields(s); return new StringBuffer(TareasManager.getTareas(Integer.parseInt(a.get(0).toString())).getIdtareaTareasParsed()); } protected StringBuffer updateFechainicioResponseCallBack(String s) { ArrayList a = AjaxUtils.splitIdFields(s); return new StringBuffer(TareasManager.getTareas(Integer.parseInt(a.get(0).toString())).getFechainicioTareasParsed()); } protected StringBuffer updateHorasResponseCallBack(String s) { ArrayList a = AjaxUtils.splitIdFields(s); return new StringBuffer(TareasManager.getTareas(Integer.parseInt(a.get(0).toString())).getHorasTareasParsed()); } protected StringBuffer updateIdordenResponseCallBack(String s) { ArrayList a = AjaxUtils.splitIdFields(s); return new StringBuffer(TareasManager.getTareas(Integer.parseInt(a.get(0).toString())).getIdordenTareasParsed()); } protected StringBuffer updateIdtipotareaResponseCallBack(String s) { ArrayList a = AjaxUtils.splitIdFields(s); return new StringBuffer(TareasManager.getTareas(Integer.parseInt(a.get(0).toString())).getIdtipotareaTareasParsed()); } protected StringBuffer updateIdcategoriaResponseCallBack(String s) { ArrayList a = AjaxUtils.splitIdFields(s); return new StringBuffer(TareasManager.getTareas(Integer.parseInt(a.get(0).toString())).getIdcategoriaTareasParsed()); } protected StringBuffer updateObservacionesResponseCallBack(String s) { ArrayList a = AjaxUtils.splitIdFields(s); return new StringBuffer(TareasManager.getTareas(Integer.parseInt(a.get(0).toString())).getObservacionesTareasParsed()); } public void serviceTareasOrdenestrabajo(HttpServletRequest request, HttpServletResponse response) throws IOException, TorqueException, ServletException { String cadena=null; Criteria c= new Criteria(); int claveId=-1; claveId=WebUtils.getintParam(request, "ordenestrabajo.IDORDEN"); if (claveId!=-1) { c.add(OrdenestrabajoPeer.IDORDEN, claveId); } c.addAscendingOrderByColumn(OrdenestrabajoPeer.IDORDEN); OrdenestrabajoGroupBean trgb = OrdenestrabajoManager.getOrdenestrabajos(c); if (trgb.getTotalSize()!=0) { cadena = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>"; cadena = cadena + "<result><tareas.IDORDEN>" + trgb.getOrdenestrabajo(0).getULContentOrdenestrabajoParsed() + "</tareas.IDORDEN></result>"; } xmlResponseService(response, new StringBuffer(cadena)); } public void serviceTareasTipotareas(HttpServletRequest request, HttpServletResponse response) throws IOException, TorqueException, ServletException { String cadena=null; Criteria c= new Criteria(); int claveId=-1; claveId=WebUtils.getintParam(request, "tipotareas.IDTIPOTAREA"); if (claveId!=-1) { c.add(TipotareasPeer.IDTIPOTAREA, claveId); } c.addAscendingOrderByColumn(TipotareasPeer.IDTIPOTAREA); TipotareasGroupBean trgb = TipotareasManager.getTipotareass(c); if (trgb.getTotalSize()!=0) { cadena = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>"; cadena = cadena + "<result><tareas.IDTIPOTAREA>" + trgb.getTipotareas(0).getULContentTipotareasParsed() + "</tareas.IDTIPOTAREA></result>"; } xmlResponseService(response, new StringBuffer(cadena)); } public void serviceTareasCategorias(HttpServletRequest request, HttpServletResponse response) throws IOException, TorqueException, ServletException { String cadena=null; Criteria c= new Criteria(); int claveId=-1; claveId=WebUtils.getintParam(request, "categorias.IDCATEGORIA"); if (claveId!=-1) { c.add(CategoriasPeer.IDCATEGORIA, claveId); } c.addAscendingOrderByColumn(CategoriasPeer.IDCATEGORIA); CategoriasGroupBean trgb = CategoriasManager.getCategoriass(c); if (trgb.getTotalSize()!=0) { cadena = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>"; cadena = cadena + "<result><tareas.IDCATEGORIA>" + trgb.getCategorias(0).getULContentCategoriasParsed() + "</tareas.IDCATEGORIA></result>"; } xmlResponseService(response, new StringBuffer(cadena)); } public void serviceGetTareasDetallePdf(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { utf8RequestService(request); String[] getMethodos= new String[] { TareasHelper.IDTAREA_GET_METHOD_NAME ,TareasHelper.FECHAINICIO_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.HORAS_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.IDORDEN_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.IDTIPOTAREA_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.IDCATEGORIA_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.OBSERVACIONES_GET_METHOD_NAME+"TareasParsed" }; TareasGroupBean tgb = new TareasGroupBean(); try { tgb.setElemento(TareasHelper.getTareas(request)); } catch (TorqueException e) { logger.severe(e.getMessage()); } byte[] content = PdfUtils.getBytes(replaceStringBuffer(tgb.buildXml(getMethodos, null,"ISO-8859-1"),"n/a"," "), tareas_transformer,"ISO-8859-1"); response.addHeader("content-disposition","attachment;filename=Tareas.pdf"); response.setContentType("application/pdf"); response.setHeader("Cache-Control", "");//para que funcione en IE response.setContentLength(content.length); response.getOutputStream().write(content); response.getOutputStream().flush(); response.getOutputStream().close(); } public void serviceTareasTableContentPdf(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { utf8RequestService(request); Criteria c= new Criteria(); String paramQuery = WebUtils.getStringParam(request, "query"); if ((paramQuery != null)&& (paramQuery.compareTo("")!=0) ) c = TareasManager.buildSearchCriteria(paramQuery); c =criteriaTareasTableContent(request,c); TareasGroupBean tgb = TareasManager.getTareass(c); String[] methodos= new String[] { TareasHelper.FECHAINICIO_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.HORAS_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.IDORDEN_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.IDTIPOTAREA_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.IDCATEGORIA_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.OBSERVACIONES_GET_METHOD_NAME+"TareasParsed" }; byte[] content = PdfUtils.getBytes(replaceStringBuffer(tgb.buildXml(methodos, null,"ISO-8859-1"),"n/a"," "), tareass_transformer,"ISO-8859-1"); response.addHeader("content-disposition","attachment;filename=ListaTareas.pdf"); response.setContentType("application/pdf"); response.setHeader("Cache-Control", "");//para que funcione en IE response.setContentLength(content.length); response.getOutputStream().write(content); response.getOutputStream().flush(); response.getOutputStream().close(); } public void serviceCosteCategoriasTareas(HttpServletRequest request, HttpServletResponse response) throws IOException, TorqueException, ServletException { String cadena=null; Criteria c= new Criteria(); String claveId=""; claveId=WebUtils.getStringParam(request, "tareas.IDCATEGORIA"); if (claveId!="") { int iId = Integer.parseInt(claveId.split("-")[0]); c.add(CategoriasPeer.IDCATEGORIA, iId); } CategoriasGroupBean trgb = CategoriasManager.getCategoriass(c); if (trgb.getTotalSize()!=0) { cadena = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>"; cadena = cadena + "<result><tareas.COSTECATEGORIA>" + trgb.getCategorias(0).getCoste() + "</tareas.COSTECATEGORIA></result>"; } xmlResponseService(response, new StringBuffer(cadena)); } }
Esleelkartea/instelec-app
instelecapp_v1.0.0_src/src/net/idtoki/instelec/controller/TareasController.java
Java
gpl-2.0
18,850
// SPDX-License-Identifier: GPL-2.0 #include <errno.h> #include <QtBluetooth/QBluetoothAddress> #include <QLowEnergyController> #include <QLowEnergyService> #include <QCoreApplication> #include <QElapsedTimer> #include <QEventLoop> #include <QThread> #include <QTimer> #include <QDebug> #include <QLoggingCategory> #include <libdivecomputer/version.h> #include "libdivecomputer.h" #include "core/qt-ble.h" #include "core/btdiscovery.h" #if defined(SSRF_CUSTOM_IO) #include <libdivecomputer/custom_io.h> #define BLE_TIMEOUT 12000 // 12 seconds seems like a very long time to wait #define DEBUG_THRESHOLD 20 static int debugCounter; #define IS_HW(_d) same_string((_d)->vendor, "Heinrichs Weikamp") #define IS_SHEARWATER(_d) same_string((_d)->vendor, "Shearwater") #define MAXIMAL_HW_CREDIT 255 #define MINIMAL_HW_CREDIT 32 extern "C" { void waitFor(int ms) { Q_ASSERT(QCoreApplication::instance()); Q_ASSERT(QThread::currentThread()); QElapsedTimer timer; timer.start(); do { QCoreApplication::processEvents(QEventLoop::AllEvents, ms); QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete); QThread::msleep(10); } while (timer.elapsed() < ms); } void BLEObject::serviceStateChanged(QLowEnergyService::ServiceState s) { Q_UNUSED(s) QList<QLowEnergyCharacteristic> list; auto service = qobject_cast<QLowEnergyService*>(sender()); if (service) list = service->characteristics(); Q_FOREACH(QLowEnergyCharacteristic c, list) { qDebug() << " " << c.uuid().toString(); } } void BLEObject::characteristcStateChanged(const QLowEnergyCharacteristic &c, const QByteArray &value) { if (IS_HW(device)) { if (c.uuid() == hwAllCharacteristics[HW_OSTC_BLE_DATA_TX]) { hw_credit--; receivedPackets.append(value); if (hw_credit == MINIMAL_HW_CREDIT) setHwCredit(MAXIMAL_HW_CREDIT - MINIMAL_HW_CREDIT); } else { qDebug() << "ignore packet from" << c.uuid() << value.toHex(); } } else { receivedPackets.append(value); } } void BLEObject::characteristicWritten(const QLowEnergyCharacteristic &c, const QByteArray &value) { if (IS_HW(device)) { if (c.uuid() == hwAllCharacteristics[HW_OSTC_BLE_CREDITS_RX]) { bool ok; hw_credit += value.toHex().toInt(&ok, 16); isCharacteristicWritten = true; } } else { if (debugCounter < DEBUG_THRESHOLD) qDebug() << "BLEObject::characteristicWritten"; } } void BLEObject::writeCompleted(const QLowEnergyDescriptor &d, const QByteArray &value) { Q_UNUSED(value) Q_UNUSED(d) qDebug() << "BLE write completed"; } void BLEObject::addService(const QBluetoothUuid &newService) { qDebug() << "Found service" << newService; bool isStandardUuid = false; newService.toUInt16(&isStandardUuid); if (IS_HW(device)) { /* The HW BT/BLE piece or hardware uses, what we * call here, "a Standard UUID. It is standard because the Telit/Stollmann * manufacturer applied for an own UUID for its product, and this was granted * by the Bluetooth SIG. */ if (newService != QUuid("{0000fefb-0000-1000-8000-00805f9b34fb}")) return; // skip all services except the right one } else if (isStandardUuid) { qDebug () << " .. ignoring standard service"; return; } auto service = controller->createServiceObject(newService, this); qDebug() << " .. created service object" << service; if (service) { services.append(service); connect(service, &QLowEnergyService::stateChanged, this, &BLEObject::serviceStateChanged); connect(service, &QLowEnergyService::characteristicChanged, this, &BLEObject::characteristcStateChanged); connect(service, &QLowEnergyService::characteristicWritten, this, &BLEObject::characteristicWritten); connect(service, &QLowEnergyService::descriptorWritten, this, &BLEObject::writeCompleted); service->discoverDetails(); } } BLEObject::BLEObject(QLowEnergyController *c, dc_user_device_t *d) { controller = c; device = d; debugCounter = 0; } BLEObject::~BLEObject() { qDebug() << "Deleting BLE object"; } dc_status_t BLEObject::write(const void *data, size_t size, size_t *actual) { Q_UNUSED(actual) // that seems like it might cause problems if (!receivedPackets.isEmpty()) { qDebug() << ".. write HIT with still incoming packets in queue"; } QList<QLowEnergyCharacteristic> list = preferredService()->characteristics(); if (list.isEmpty()) return DC_STATUS_IO; QByteArray bytes((const char *)data, (int) size); const QLowEnergyCharacteristic &c = list.constFirst(); QLowEnergyService::WriteMode mode; mode = (c.properties() & QLowEnergyCharacteristic::WriteNoResponse) ? QLowEnergyService::WriteWithoutResponse : QLowEnergyService::WriteWithResponse; if (IS_SHEARWATER(device)) bytes.prepend("\1\0", 2); preferredService()->writeCharacteristic(c, bytes, mode); return DC_STATUS_SUCCESS; } dc_status_t BLEObject::read(void *data, size_t size, size_t *actual) { if (actual) *actual = 0; if (receivedPackets.isEmpty()) { QList<QLowEnergyCharacteristic> list = preferredService()->characteristics(); if (list.isEmpty()) return DC_STATUS_IO; int msec = BLE_TIMEOUT; while (msec > 0 && receivedPackets.isEmpty()) { waitFor(100); msec -= 100; }; } // Still no packet? if (receivedPackets.isEmpty()) return DC_STATUS_IO; QByteArray packet = receivedPackets.takeFirst(); if (IS_SHEARWATER(device)) packet.remove(0,2); if ((size_t)packet.size() > size) return DC_STATUS_NOMEMORY; memcpy((char *)data, packet.data(), packet.size()); if (actual) *actual += packet.size(); return DC_STATUS_SUCCESS; } dc_status_t BLEObject::setHwCredit(unsigned int c) { /* The Terminal I/O client transmits initial UART credits to the server (see 6.5). * * Notice that we have to write to the characteristic here, and not to its * descriptor as for the enabeling of notifications or indications. * * Futher notice that this function has the implicit effect of processing the * event loop (due to waiting for the confirmation of the credit request). * So, as characteristcStateChanged will be triggered, while receiving * data from the OSTC, these are processed too. */ QList<QLowEnergyCharacteristic> list = preferredService()->characteristics(); isCharacteristicWritten = false; preferredService()->writeCharacteristic(list[HW_OSTC_BLE_CREDITS_RX], QByteArray(1, c), QLowEnergyService::WriteWithResponse); /* And wait for the answer*/ int msec = BLE_TIMEOUT; while (msec > 0 && !isCharacteristicWritten) { waitFor(100); msec -= 100; }; if (!isCharacteristicWritten) return DC_STATUS_TIMEOUT; return DC_STATUS_SUCCESS; } dc_status_t BLEObject::setupHwTerminalIo(QList<QLowEnergyCharacteristic> allC) { /* This initalizes the Terminal I/O client as described in * http://www.telit.com/fileadmin/user_upload/products/Downloads/sr-rf/BlueMod/TIO_Implementation_Guide_r04.pdf * Referenced section numbers below are from that document. * * This is for all HW computers, that use referenced BT/BLE hardware module from Telit * (formerly Stollmann). The 16 bit UUID 0xFEFB (or a derived 128 bit UUID starting with * 0x0000FEFB is a clear indication that the OSTC is equipped with this BT/BLE hardware. */ if (allC.length() != 4) { qDebug() << "This should not happen. HW/OSTC BT/BLE device without 4 Characteristics"; return DC_STATUS_IO; } /* The Terminal I/O client subscribes to indications of the UART credits TX * characteristic (see 6.4). * * Notice that indications are subscribed to by writing 0x0200 to its descriptor. This * can be understood by looking for Client Characteristic Configuration, Assigned * Number: 0x2902. Enabling/Disabeling is setting the proper bit, and they * differ for indications and notifications. */ QLowEnergyDescriptor d = allC[HW_OSTC_BLE_CREDITS_TX].descriptors().first(); preferredService()->writeDescriptor(d, QByteArray::fromHex("0200")); /* The Terminal I/O client subscribes to notifications of the UART data TX * characteristic (see 6.2). */ d = allC[HW_OSTC_BLE_DATA_TX].descriptors().first(); preferredService()->writeDescriptor(d, QByteArray::fromHex("0100")); /* The Terminal I/O client transmits initial UART credits to the server (see 6.5). */ return setHwCredit(MAXIMAL_HW_CREDIT); } dc_status_t qt_ble_open(dc_custom_io_t *io, dc_context_t *context, const char *devaddr) { Q_UNUSED(context) debugCounter = 0; QLoggingCategory::setFilterRules(QStringLiteral("qt.bluetooth* = true")); /* * LE-only devices get the "LE:" prepended by the scanning * code, so that the rfcomm code can see they only do LE. * * We just skip that prefix (and it doesn't always exist, * since the device may support both legacy BT and LE). */ if (!strncmp(devaddr, "LE:", 3)) devaddr += 3; // HACK ALERT! Qt 5.9 needs this for proper Bluez operation qputenv("QT_DEFAULT_CENTRAL_SERVICES", "1"); #if defined(Q_OS_MACOS) || defined(Q_OS_IOS) QBluetoothDeviceInfo remoteDevice = getBtDeviceInfo(devaddr); QLowEnergyController *controller = QLowEnergyController::createCentral(remoteDevice); #else // this is deprecated but given that we don't use Qt to scan for // devices on Android, we don't have QBluetoothDeviceInfo for the // paired devices and therefore cannot use the newer interfaces // that are preferred starting with Qt 5.7 QBluetoothAddress remoteDeviceAddress(devaddr); QLowEnergyController *controller = new QLowEnergyController(remoteDeviceAddress); #endif qDebug() << "qt_ble_open(" << devaddr << ")"; if (IS_SHEARWATER(io->user_device)) controller->setRemoteAddressType(QLowEnergyController::RandomAddress); // Try to connect to the device controller->connectToDevice(); // Create a timer. If the connection doesn't succeed after five seconds or no error occurs then stop the opening step int msec = BLE_TIMEOUT; while (msec > 0 && controller->state() == QLowEnergyController::ConnectingState) { waitFor(100); msec -= 100; }; switch (controller->state()) { case QLowEnergyController::ConnectedState: qDebug() << "connected to the controller for device" << devaddr; break; default: qDebug() << "failed to connect to the controller " << devaddr << "with error" << controller->errorString(); report_error("Failed to connect to %s: '%s'", devaddr, controller->errorString().toUtf8().data()); controller->disconnectFromDevice(); delete controller; return DC_STATUS_IO; } /* We need to discover services etc here! */ BLEObject *ble = new BLEObject(controller, io->user_device); ble->connect(controller, SIGNAL(serviceDiscovered(QBluetoothUuid)), SLOT(addService(QBluetoothUuid))); qDebug() << " .. discovering services"; controller->discoverServices(); msec = BLE_TIMEOUT; while (msec > 0 && controller->state() == QLowEnergyController::DiscoveringState) { waitFor(100); msec -= 100; }; qDebug() << " .. done discovering services"; if (ble->preferredService() == nullptr) { qDebug() << "failed to find suitable service on" << devaddr; report_error("Failed to find suitable service on '%s'", devaddr); controller->disconnectFromDevice(); delete controller; return DC_STATUS_IO; } qDebug() << " .. discovering details"; msec = BLE_TIMEOUT; while (msec > 0 && ble->preferredService()->state() == QLowEnergyService::DiscoveringServices) { waitFor(100); msec -= 100; }; if (ble->preferredService()->state() != QLowEnergyService::ServiceDiscovered) { qDebug() << "failed to find suitable service on" << devaddr; report_error("Failed to find suitable service on '%s'", devaddr); controller->disconnectFromDevice(); delete controller; return DC_STATUS_IO; } qDebug() << " .. enabling notifications"; /* Enable notifications */ QList<QLowEnergyCharacteristic> list = ble->preferredService()->characteristics(); if (!list.isEmpty()) { const QLowEnergyCharacteristic &c = list.constLast(); if (IS_HW(io->user_device)) { dc_status_t r = ble->setupHwTerminalIo(list); if (r != DC_STATUS_SUCCESS) return r; } else { QList<QLowEnergyDescriptor> l = c.descriptors(); qDebug() << "Descriptor list with" << l.length() << "elements"; QLowEnergyDescriptor d; foreach(d, l) qDebug() << "Descriptor:" << d.name() << "uuid:" << d.uuid().toString(); if (!l.isEmpty()) { bool foundCCC = false; foreach (d, l) { if (d.type() == QBluetoothUuid::ClientCharacteristicConfiguration) { // pick the correct characteristic foundCCC = true; break; } } if (!foundCCC) // if we didn't find a ClientCharacteristicConfiguration, try the first one d = l.first(); qDebug() << "now writing \"0x0100\" to the descriptor" << d.uuid().toString(); ble->preferredService()->writeDescriptor(d, QByteArray::fromHex("0100")); } } } // Fill in info io->userdata = (void *)ble; return DC_STATUS_SUCCESS; } dc_status_t qt_ble_close(dc_custom_io_t *io) { BLEObject *ble = (BLEObject *) io->userdata; io->userdata = NULL; delete ble; return DC_STATUS_SUCCESS; } static void checkThreshold() { if (++debugCounter == DEBUG_THRESHOLD) { QLoggingCategory::setFilterRules(QStringLiteral("qt.bluetooth* = false")); qDebug() << "turning off further BT debug output"; } } dc_status_t qt_ble_read(dc_custom_io_t *io, void* data, size_t size, size_t *actual) { checkThreshold(); BLEObject *ble = (BLEObject *) io->userdata; return ble->read(data, size, actual); } dc_status_t qt_ble_write(dc_custom_io_t *io, const void* data, size_t size, size_t *actual) { checkThreshold(); BLEObject *ble = (BLEObject *) io->userdata; return ble->write(data, size, actual); } } /* extern "C" */ #endif
neolit123/subsurface
core/qt-ble.cpp
C++
gpl-2.0
13,635
package com.uvic.textshare.service.rest; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Consumes; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.json.JSONException; import org.json.JSONObject; import java.text.ParseException; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.concurrent.TimeUnit; import java.io.UnsupportedEncodingException; import java.lang.String; import com.uvic.textshare.service.matching.MatchingFunction; import com.uvic.textshare.service.model.*; import com.google.appengine.api.users.*; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.Query.Filter; import com.google.appengine.api.datastore.Query.FilterPredicate; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.appengine.api.datastore.Query.CompositeFilterOperator; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import com.google.gson.Gson; @SuppressWarnings("unused") @Path("/") public class TextbookResource { private static int numberOf_offered_books; private static int numberOf_requested_books; private static int numberOf_matches; MatchingFunction matchingFunction = new MatchingFunction(); String matchDate; /* * * Start of REST Methods * */ @POST @Path("/retrieve") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public String getTextbook(String input) { try { //Create a filter for retrieving all the books associated with that user JSONObject obj = new JSONObject(input); String user_id = obj.getString("uid"); Filter userFilter = new FilterPredicate("uid", FilterOperator.EQUAL, user_id); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Query q = new Query("User").setFilter(userFilter); Entity user = datastore.prepare(q).asSingleEntity(); if(user == null && !user_id.equals("")) { createUser(obj); return "[]"; } else { Query q2 = new Query("Textbook").setFilter(userFilter); PreparedQuery pd2 = datastore.prepare(q2); List<Entity> textbooks = pd2.asList(FetchOptions.Builder.withDefaults()); String json = new Gson().toJson(textbooks); return json; } } catch(NullPointerException e) { e.printStackTrace(); return "[]"; //something went wrong } } @POST @Path("/add") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public String addTextbook(String input) throws ParseException { try { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); JSONObject text = new JSONObject(input); Date addDate = new Date(); matchDate = "emtpy"; String response = matchingFunction.checkForMatch( text.getString("isbn"), text.getString("uid"), text.getString("type"), text.getString("title"), text.getDouble("condition"), text.getString("edition")); String[] parts = response.split("-"); String matched = parts[0]; if(matched.equals("yes")) { matchDate = parts[1]; numberOf_matches++; } double radius = text.getDouble("radius"); radius = radius / 1000.0; if(radius > 30 || radius < 5) { radius = 15.0; } Entity textbook = new Entity("Textbook"); textbook.setProperty("uid", text.getString("uid")); textbook.setProperty("type", text.getString("type")); textbook.setUnindexedProperty("title", text.getString("title")); textbook.setUnindexedProperty("author", text.getString("author")); textbook.setProperty("isbn", text.getString("isbn")); textbook.setProperty("edition", text.getString("edition")); textbook.setProperty("condition", text.getDouble("condition")); textbook.setProperty("date", addDate); textbook.setProperty("matchDate", matchDate); textbook.setProperty("matched", matched); textbook.setUnindexedProperty("image", text.getString("image")); textbook.setUnindexedProperty("lat", text.getDouble("lat")); textbook.setUnindexedProperty("lon", text.getDouble("lon")); textbook.setUnindexedProperty("radius", radius); datastore.put(textbook); String bookOwner = text.getString("uid"); String typeOfEntry = text.getString("type"); updateUserKarma(bookOwner, typeOfEntry, 5); if(typeOfEntry.equals("offer")) TextbookResource.numberOf_offered_books++; else TextbookResource.numberOf_requested_books++; String json = new Gson().toJson(textbook); return json; } catch(NullPointerException e) { e.printStackTrace(); return "{}"; //something went wrong! } } @POST @Path("/delete") @Consumes(MediaType.APPLICATION_JSON) public void deleteTextbook(String input) throws JSONException { try { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); JSONObject obj = new JSONObject(input); Long id = (long) obj.getDouble("id"); Key textbookKey = KeyFactory.createKey("Textbook", id); datastore.delete(textbookKey); } catch(NullPointerException e) { e.printStackTrace(); } } @POST @Path("/updateUserRadius") @Consumes(MediaType.APPLICATION_JSON) public void updateUserRadius(String input) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); try { JSONObject obj = new JSONObject(input); String uid = obj.getString("uid"); double radius = obj.getDouble("radius"); radius = radius / 1000.0; if(radius > 30 || radius < 5) { radius = 15.0; } Filter userFilter = new FilterPredicate("uid", FilterOperator.EQUAL, uid); Query q = new Query("User").setFilter(userFilter); Entity user = datastore.prepare(q).asSingleEntity(); user.setUnindexedProperty("radius", radius); datastore.put(user); q = new Query("Textbook").setFilter(userFilter); List<Entity> textbooks = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()); if(!textbooks.isEmpty()) { for(int i = 0; i < textbooks.size(); i++) { Delay.oneSecondDelay(); Entity textbook = textbooks.get(i); textbook.setUnindexedProperty("radius", radius); datastore.put(textbook); } } } catch(NullPointerException e) { e.printStackTrace(); } } @POST @Path("/updateUserLocation") @Consumes(MediaType.APPLICATION_JSON) public void updateUserLocation(String input) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); try { JSONObject obj = new JSONObject(input); String uid = obj.getString("uid"); double lat = obj.getDouble("lat"); double lon = obj.getDouble("lon"); Filter userFilter = new FilterPredicate("uid", FilterOperator.EQUAL, uid); Query q = new Query("User").setFilter(userFilter); Entity user = datastore.prepare(q).asSingleEntity(); user.setUnindexedProperty("lat", lat); user.setUnindexedProperty("lon", lon); datastore.put(user); q = new Query("Textbook").setFilter(userFilter); List<Entity> textbooks = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()); if(!textbooks.isEmpty()) { for(int i = 0; i < textbooks.size(); i++) { Delay.oneSecondDelay(); Entity textbook = textbooks.get(i); textbook.setUnindexedProperty("lat", lat); textbook.setUnindexedProperty("lon", lon); datastore.put(textbook); } } } catch(NullPointerException e) { e.printStackTrace(); } } @POST @Path("/unmatchTextbook") @Consumes(MediaType.APPLICATION_JSON) public void unmatchTextbook(String input) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); try { JSONObject obj = new JSONObject(input); Long id = (long) obj.getDouble("id"); String title = obj.getString("title"); String isbn = obj.getString("isbn"); String type = obj.getString("type"); String uid = obj.getString("uid"); String matchDate = obj.getString("matchDate"); double condition = obj.getDouble("condition"); String edition = obj.getString("edition"); String uidTwo; String typeTwo; if(type.equals("offer")) typeTwo = "request"; else typeTwo = "offer"; //Delete the match entry and retrieve other user's UID. Filter matchFilter = new FilterPredicate("matchDate", FilterOperator.EQUAL, matchDate); Query q = new Query("Match").setFilter(matchFilter); Entity match = datastore.prepare(q).asSingleEntity(); if(!uid.equals((String) match.getProperty("userOneId"))) uidTwo = (String) match.getProperty("userOneId"); else uidTwo = (String) match.getProperty("userTwoId"); Key matchKey = match.getKey(); datastore.delete(matchKey); Delay.oneSecondDelay(); //Check for a new match. Omit matching each other again. String matchedOne = matchingFunction.checkForMatch(isbn, uid, type, title, condition, edition); Delay.oneSecondDelay(); String matchedTwo = matchingFunction.checkForMatch(isbn, uidTwo, typeTwo, title, condition, edition); //Update database based on the result of new searches for matches. if(matchedOne.equals("no")) { Key textbookKey = KeyFactory.createKey("Textbook", id); Query q2 = new Query(textbookKey); Entity textbook = datastore.prepare(q2).asSingleEntity(); textbook.setProperty("matched", "no"); textbook.setProperty("matchDate", null); datastore.put(textbook); } else { String[] parts = matchedOne.split("-"); String matchDateOne = parts[1]; Key textbookKey = KeyFactory.createKey("Textbook", id); Query q2 = new Query(textbookKey); Entity textbook = datastore.prepare(q2).asSingleEntity(); textbook.setProperty("matched", "yes"); textbook.setProperty("matchDate", matchDateOne); datastore.put(textbook); } Filter isbnFilter = new FilterPredicate("isbn", FilterOperator.EQUAL,isbn); Filter uidFilter = new FilterPredicate("uid", FilterOperator.EQUAL, uidTwo); Filter searchFilter = CompositeFilterOperator.and(isbnFilter, uidFilter); Delay.oneSecondDelay(); if(matchedTwo.equals("no")) { q = new Query("Textbook").setFilter(searchFilter); Entity textbookTwo = datastore.prepare(q).asSingleEntity(); textbookTwo.setProperty("matched", "no"); textbookTwo.setProperty("matchDate", null); datastore.put(textbookTwo); } else { String[] parts = matchedTwo.split("-"); String matchDateTwo = parts[1]; q = new Query("Textbook").setFilter(searchFilter); Entity textbookTwo = datastore.prepare(q).asSingleEntity(); textbookTwo.setProperty("matched", "yes"); textbookTwo.setProperty("matchDate", matchDateTwo); datastore.put(textbookTwo); } } catch(NullPointerException e) { e.printStackTrace(); } } @POST @Path("/completeMatch") @Consumes(MediaType.APPLICATION_JSON) public void completeMatch(String input) { try { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); JSONObject obj = new JSONObject(input); Long idOfInitiator = (long) obj.getDouble("id"); String uidOfInitiator = obj.getString("uid"); String matchDate = obj.getString("matchDate"); String type = obj.getString("type"); String uidofMatch; //Delete the match entry Filter matchFilter = new FilterPredicate("matchDate", FilterOperator.EQUAL, matchDate); Query q = new Query("Match").setFilter(matchFilter); Entity match = datastore.prepare(q).asSingleEntity(); if(!uidOfInitiator.equals((String) match.getProperty("userOneId"))) uidofMatch = (String) match.getProperty("userOneId"); else uidofMatch = (String) match.getProperty("userTwoId"); Key matchKey = match.getKey(); datastore.delete(matchKey); //Delete Books Key textbookKey = KeyFactory.createKey("Textbook", idOfInitiator); datastore.delete(textbookKey); Filter uidFilter = new FilterPredicate("uid", FilterOperator.EQUAL, uidofMatch); Filter searchFilter = CompositeFilterOperator.and(uidFilter, matchFilter); q = new Query("Textbook").setFilter(searchFilter); Entity textbook = datastore.prepare(q).asSingleEntity(); matchKey = textbook.getKey(); datastore.delete(matchKey); } catch(NullPointerException e) { e.printStackTrace(); } } @POST @Path("/getUser") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public String getUser(String input) { try { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); JSONObject obj = new JSONObject(input); String uid = obj.getString("uid"); Filter userFilter = new FilterPredicate("uid", FilterOperator.EQUAL, uid); Query q = new Query("User").setFilter(userFilter); Entity user = datastore.prepare(q).asSingleEntity(); if(user == null) return "{}"; String json = new Gson().toJson(user); return json; } catch(NullPointerException e) { e.printStackTrace(); return "{}"; } } @GET @Path("/getLastFiveBooks") @Produces(MediaType.APPLICATION_JSON) public String getLastFiveBooks() { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Query query = new Query("Textbook").addSort("date", Query.SortDirection.DESCENDING); List<Entity> textbooks = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(5)); String json = new Gson().toJson(textbooks); return json; } @GET @Path("/getStatistics") @Produces(MediaType.APPLICATION_JSON) public String getStatistics() { Statistics stats = new Statistics(numberOf_offered_books, numberOf_requested_books, numberOf_matches); String json = new Gson().toJson(stats); return json; } /* * * End of REST Methods * */ /* * * Start of Support Methods * */ private void createUser(JSONObject obj) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Entity user = new Entity("User"); user.setUnindexedProperty("name", obj.getString("name")); user.setProperty("uid", obj.getString("uid")); user.setUnindexedProperty("email", obj.getString("email")); user.setUnindexedProperty("lat", obj.getDouble("lat")); user.setUnindexedProperty("lon", obj.getDouble("lon")); user.setUnindexedProperty("request_karma", 0); user.setUnindexedProperty("offer_karma", 0); user.setUnindexedProperty("radius", 15.0); //default value for radius. datastore.put(user); } private void updateUserKarma(String uid, String type, int points) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Filter userFilter = new FilterPredicate("uid", FilterOperator.EQUAL, uid); Query q = new Query("User").setFilter(userFilter); Entity user = datastore.prepare(q).asSingleEntity(); int updatedKarma; if(type.equals("offer")) { updatedKarma = Integer.parseInt(user.getProperty("offer_karma").toString()); updatedKarma += 5; user.setUnindexedProperty("offer_karma", updatedKarma); } else { updatedKarma = Integer.parseInt(user.getProperty("request_karma").toString()); updatedKarma += 5; user.setUnindexedProperty("request_karma", updatedKarma); } datastore.put(user); } /* * * End of Support Methods * */ }
Brkk/flybrary
src/main/java/com/uvic/textshare/service/rest/TextbookResource.java
Java
gpl-2.0
16,036
/* Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** @file @brief Implementation of name resolution stage @defgroup Query_Resolver Query Resolver @{ */ #include "sql_select.h" #include "sql_resolver.h" #include "sql_optimizer.h" #include "opt_trace.h" #include "sql_base.h" #include "auth_common.h" #include "opt_explain_format.h" #include "sql_test.h" // print_where #include "aggregate_check.h" static void propagate_nullability(List<TABLE_LIST> *tables, bool nullable); static const Item::enum_walk walk_subquery= Item::enum_walk(Item::WALK_POSTFIX | Item::WALK_SUBQUERY); uint build_bitmap_for_nested_joins(List<TABLE_LIST> *join_list, uint first_unused); /** Prepare query block for optimization. Resolve table and column information. Resolve all expressions (item trees), ie WHERE clause, join conditions, GROUP BY clause, HAVING clause, ORDER BY clause, LIMIT clause. Prepare all subqueries recursively as part of resolving the expressions. Apply permanent transformations to the abstract syntax tree, such as semi-join transformation, derived table transformation, elimination of constant values and redundant clauses (e.g ORDER BY, GROUP BY). @param thd thread handler @returns false if success, true if error @note on privilege checking for SELECT query that possibly contains view or derived table references: - When this function is called, it is assumed that the precheck() function has been called. precheck() ensures that the user has some SELECT privileges to the tables involved in the query. When resolving views it has also been established that the user has some privileges for them. To prepare a view for privilege checking, it is also needed to call check_view_privileges() after views have been merged into the query. This is not necessary for unnamed derived tables since it has already been established that we have SELECT privileges for the underlying tables by the precheck functions. (precheck() checks a query without resolved views, ie. before tables are opened, so underlying tables of views are not yet available). - When a query block is resolved, always ensure that the user has SELECT privileges to the columns referenced in the WHERE clause, the join conditions, the GROUP BY clause, the HAVING clause and the ORDER BY clause. - When resolving the outer-most query block, ensure that the user also has SELECT privileges to the columns in the selected expressions. - When setting up a derived table or view for materialization, ensure that the user has SELECT privileges to the columns in the selected expressions - Column privileges are normally checked by Item_field::fix_fields(). Exceptions are select list of derived tables/views which are checked in TABLE_LIST::setup_materialized_derived(), and natural/using join conditions that are checked in mark_common_columns(). - As far as INSERT, UPDATE and DELETE statements have the same expressions as a SELECT statement, this note applies to those statements as well. */ bool SELECT_LEX::prepare(THD *thd) { DBUG_ENTER("SELECT_LEX::prepare"); // We may do subquery transformation, or Item substitution: Prepare_error_tracker tracker(thd); DBUG_ASSERT(this == thd->lex->current_select()); DBUG_ASSERT(join == NULL); SELECT_LEX_UNIT *const unit= master_unit(); if (top_join_list.elements > 0) propagate_nullability(&top_join_list, false); is_item_list_lookup= true; Opt_trace_context * const trace= &thd->opt_trace; Opt_trace_object trace_wrapper(trace); Opt_trace_object trace_prepare(trace, "join_preparation"); trace_prepare.add_select_number(select_number); Opt_trace_array trace_steps(trace, "steps"); // Initially, "all_fields" is the select list all_fields= fields_list; /* Check that all tables, fields, conds and order are ok */ if (!(active_options() & OPTION_SETUP_TABLES_DONE)) { if (setup_tables(thd, get_table_list(), false)) DBUG_RETURN(true); if (derived_table_count && resolve_derived(thd, true)) DBUG_RETURN(true); // Wait with privilege checking until all derived tables are resolved. if (!thd->derived_tables_processing && check_view_privileges(thd, SELECT_ACL, SELECT_ACL)) DBUG_RETURN(true); } // Precompute and store the row types of NATURAL/USING joins. if (setup_natural_join_row_types(thd, join_list, &context)) DBUG_RETURN(true); Mem_root_array<Item_exists_subselect *, true> sj_candidates_local(thd->mem_root); sj_candidates= &sj_candidates_local; /* Item and Item_field CTORs will both increment some counters in current_select(), based on the current parsing context. We are not parsing anymore: any new Items created now are due to query rewriting, so stop incrementing counters. */ DBUG_ASSERT(parsing_place == CTX_NONE); parsing_place= CTX_NONE; resolve_place= RESOLVE_SELECT_LIST; /* Setup the expressions in the SELECT list. Wait with privilege checking until all derived tables are resolved, except do privilege checking for subqueries inside a derived table. */ const bool check_privs= !thd->derived_tables_processing || master_unit()->item != NULL; thd->mark_used_columns= check_privs ? MARK_COLUMNS_READ : MARK_COLUMNS_NONE; ulonglong want_privilege_saved= thd->want_privilege; thd->want_privilege= check_privs ? SELECT_ACL : 0; if (with_wild && setup_wild(thd)) DBUG_RETURN(true); if (setup_ref_array(thd)) DBUG_RETURN(true); /* purecov: inspected */ if (setup_fields(thd, ref_ptrs, fields_list, thd->want_privilege, &all_fields, true)) DBUG_RETURN(true); resolve_place= RESOLVE_NONE; const nesting_map save_allow_sum_func= thd->lex->allow_sum_func; // Do not allow local set functions for join conditions, WHERE and GROUP BY thd->lex->allow_sum_func&= ~((nesting_map)1 << nest_level); thd->mark_used_columns= MARK_COLUMNS_READ; thd->want_privilege= SELECT_ACL; // Set up join conditions and WHERE clause if (setup_conds(thd)) DBUG_RETURN(true); // Set up the GROUP BY clause int all_fields_count= all_fields.elements; if (group_list.elements && setup_group(thd)) DBUG_RETURN(true); hidden_group_field_count= all_fields.elements - all_fields_count; // Allow local set functions in HAVING and ORDER BY thd->lex->allow_sum_func|= (nesting_map)1 << nest_level; // Setup the HAVING clause if (m_having_cond) { thd->where="having clause"; having_fix_field= true; resolve_place= RESOLVE_HAVING; if (!m_having_cond->fixed && (m_having_cond->fix_fields(thd, &m_having_cond) || m_having_cond->check_cols(1))) DBUG_RETURN(true); having_fix_field= false; resolve_place= RESOLVE_NONE; } // Set up the ORDER BY clause all_fields_count= all_fields.elements; int hidden_order_field_count= 0; if (order_list.elements) { if (setup_order(thd, ref_ptrs, get_table_list(), fields_list, all_fields, order_list.first)) DBUG_RETURN(true); hidden_order_field_count= all_fields.elements - all_fields_count; } // Query block is completely resolved, restore set function allowance thd->lex->allow_sum_func= save_allow_sum_func; thd->want_privilege= want_privilege_saved; /* Permanently remove redundant parts from the query if 1) This is a subquery 2) This is the first time this query is prepared (since the transformation is permanent) 3) Not normalizing a view. Removal should take place when a query involving a view is optimized, not when the view is created */ if (unit->item && // 1) first_execution && // 2) !(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW)) // 3) { remove_redundant_subquery_clauses(thd, hidden_group_field_count, hidden_order_field_count); } if (order_list.elements && setup_order_final(thd, hidden_order_field_count)) DBUG_RETURN(true); /* purecov: inspected */ if (is_distinct() && is_grouped() && hidden_group_field_count == 0 && olap == UNSPECIFIED_OLAP_TYPE) { /* All GROUP expressions are in SELECT list, so resulting rows are distinct. ROLLUP is not specified, so adds no row. So all rows in the result set are distinct, DISTINCT is useless. @todo could remove DISTINCT if ROLLUP were specified and all GROUP expressions were non-nullable, because ROLLUP adds only NULL values. Currently, ROLLUP+DISTINCT is rejected because executor cannot handle it in all cases. */ remove_base_options(SELECT_DISTINCT); } /* Printing the expanded query should happen here and not elsewhere, because when a view is merged (when the view is opened in open_tables()), the parent query's select_lex does not yet contain a correct WHERE clause (it misses the view's merged WHERE clause). This is corrected only just above, in TABLE_LIST::prep_where(), called by setup_without_group()->setup_conds(). We also have to wait for fix_fields() on HAVING, above. At this stage, we also have properly set up Item_ref-s. */ { Opt_trace_object trace_wrapper(trace); opt_trace_print_expanded_query(thd, this, &trace_wrapper); } /* When normalizing a view (like when writing a view's body to the FRM), subquery transformations don't apply (if they did, IN->EXISTS could not be undone in favour of materialization, when optimizing a later statement using the view) */ if (unit->item && // This is a subquery this != unit->fake_select_lex && // A real query block // Not normalizing a view !(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW)) { // Query block represents a subquery within an IN/ANY/ALL/EXISTS predicate if (resolve_subquery(thd)) DBUG_RETURN(true); } if (m_having_cond && m_having_cond->with_sum_func) m_having_cond->split_sum_func2(thd, ref_ptrs, all_fields, &m_having_cond, true); if (inner_sum_func_list) { Item_sum *end=inner_sum_func_list; Item_sum *item_sum= end; do { item_sum= item_sum->next; item_sum->split_sum_func2(thd, ref_ptrs, all_fields, item_sum->ref_by, false); } while (item_sum != end); } if (inner_refs_list.elements && fix_inner_refs(thd)) DBUG_RETURN(true); /* purecov: inspected */ if (group_list.elements) { /* Because HEAP tables can't index BIT fields we need to use an additional hidden field for grouping because later it will be converted to a LONG field. Original field will remain of the BIT type and will be returned to a client. */ for (ORDER *ord= (ORDER *)group_list.first; ord; ord= ord->next) { if ((*ord->item)->type() == Item::FIELD_ITEM && (*ord->item)->field_type() == MYSQL_TYPE_BIT) { Item_field *field= new Item_field(thd, *(Item_field**)ord->item); int el= all_fields.elements; ref_ptrs[el]= field; all_fields.push_front(field); ord->item= &ref_ptrs[el]; } } } if (setup_ftfuncs(this)) /* should be after having->fix_fields */ DBUG_RETURN(true); if (query_result() && query_result()->prepare(fields_list, unit)) DBUG_RETURN(true); if (olap == ROLLUP_TYPE && resolve_rollup(thd)) DBUG_RETURN(true); /* purecov: inspected */ if (flatten_subqueries()) DBUG_RETURN(true); sj_candidates= NULL; if (!outer_select()) { /* This code is invoked in the following cases: - if this is an outer-most query block of a SELECT or multi-table UPDATE/DELETE statement. Notice that for a UNION, this applies to all query blocks. It also applies to a fake_select_lex object. - if this is one of highest-level subqueries, if the statement is something else; like subq-i in: UPDATE t1 SET col1=(subq-1), col2=(subq-2); Local transforms are applied after query block merging. This means that we avoid unnecessary invocations, as local transforms would otherwise have been performed first before query block merging and then another time after query block merging. Thus, apply_local_transforms() may run only after the top query is finished with query block merging. That's why apply_local_transforms() is initiated only by the top query, and then recurses into subqueries. */ if (apply_local_transforms(thd, true)) DBUG_RETURN(true); } DBUG_ASSERT(!thd->is_error()); DBUG_RETURN(false); } /** Apply local transformations, such as query block merging. Also perform partition pruning, which is most effective after transformations have been done. @param thd thread handler @param prune if true, then prune partitions based on const conditions @returns false if success, true if error Since this is called after flattening of query blocks, call this function while traversing the query block hierarchy top-down. */ bool SELECT_LEX::apply_local_transforms(THD *thd, bool prune) { DBUG_ENTER("SELECT_LEX::apply_local_transforms"); /* If query block contains one or more merged derived tables/views, walk through lists of columns in select lists and remove unused columns. */ if (derived_table_count && first_execution && !(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW)) delete_unused_merged_columns(&top_join_list); for (SELECT_LEX_UNIT *unit= first_inner_unit(); unit; unit= unit->next_unit()) { for (SELECT_LEX *sl= unit->first_select(); sl; sl= sl->next_select()) { // Prune all subqueries, regardless of passed argument if (sl->apply_local_transforms(thd, true)) DBUG_RETURN(true); } if (unit->fake_select_lex && unit->fake_select_lex->apply_local_transforms(thd, false)) DBUG_RETURN(true); } if (first_execution && !(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW)) { /* The following code will allocate the new items in a permanent MEMROOT for prepared statements and stored procedures. */ Prepared_stmt_arena_holder ps_arena_holder(thd); // Convert all outer joins to inner joins if possible if (simplify_joins(thd, &top_join_list, true, false, &m_where_cond)) DBUG_RETURN(true); if (record_join_nest_info(&top_join_list)) DBUG_RETURN(true); build_bitmap_for_nested_joins(&top_join_list, 0); /* Here are reasons why we do the following check here (i.e. late). * setup_fields () may have done split_sum_func () on aggregate items of the SELECT list, so for reliable comparison of the ORDER BY list with the SELECT list, we need to wait until split_sum_func() has been done on the ORDER BY list. * we get "most of the time" fixed items, which is always a good thing. Some outer references may not be fixed, though. * we need nested_join::used_tables, and this member is set in simplify_joins() * simplify_joins() does outer-join-to-inner conversion, which increases opportunities for functional dependencies (weak-to-strong, which is unusable, becomes strong-to-strong). * check_only_full_group_by() is dependent on processing done by simplify_joins() (for example it uses the value of SELECT_LEX::outer_join). The drawback is that the checks are after resolve_subquery(), so can meet strange "internally added" items. Note that when we are creating a view, simplify_joins() doesn't run so check_only_full_group_by() cannot run, any error will be raised only when the view is later used (SELECTed...) */ if ((thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY) && (is_distinct() || is_grouped()) && check_only_full_group_by(thd)) DBUG_RETURN(true); } fix_prepare_information(thd); /* Prune partitions for all query blocks after query block merging, if pruning is wanted. */ if (partitioned_table_count && prune) { for (TABLE_LIST *tbl= leaf_tables; tbl; tbl= tbl->next_leaf) { /* This will only prune constant conditions, which will be used for lock pruning. */ if (prune_partitions(thd, tbl->table, tbl->join_cond() ? tbl->join_cond() : m_where_cond)) DBUG_RETURN(true); /* purecov: inspected */ } } DBUG_RETURN(false); } /** Check if the subquery predicate can be executed via materialization. @param predicate IN subquery predicate @param thd THD @param select_lex SELECT_LEX of the subquery @param outer Parent SELECT_LEX (outer to subquery) @return TRUE if subquery allows materialization, FALSE otherwise. */ bool subquery_allows_materialization(Item_in_subselect *predicate, THD *thd, SELECT_LEX *select_lex, const SELECT_LEX *outer) { const uint elements= predicate->unit->first_select()->item_list.elements; DBUG_ENTER("subquery_allows_materialization"); DBUG_ASSERT(elements >= 1); DBUG_ASSERT(predicate->left_expr->cols() == elements); OPT_TRACE_TRANSFORM(&thd->opt_trace, trace_wrapper, trace_mat, select_lex->select_number, "IN (SELECT)", "materialization"); const char *cause= NULL; if (predicate->substype() != Item_subselect::IN_SUBS) { // Subq-mat cannot handle 'outer_expr > {ANY|ALL}(subq)'... cause= "not an IN predicate"; } else if (select_lex->is_part_of_union()) { // Subquery must be a single query specification clause (not a UNION) cause= "in UNION"; } else if (!select_lex->master_unit()->first_select()->leaf_tables) { // Subquery has no tables, hence no point in materializing. cause= "no inner tables"; } else if (!outer->join) { /* Maybe this is a subquery of a single table UPDATE/DELETE (TODO: handle this by switching to multi-table UPDATE/DELETE). */ cause= "parent query has no JOIN"; } else if (!outer->leaf_tables) { // The upper query is SELECT ... FROM DUAL. No gain in materializing. cause= "no tables in outer query"; } else if (predicate->dependent_before_in2exists()) { /* Subquery should not be correlated; the correlation due to predicates injected by IN->EXISTS does not count as we will remove them if we choose materialization. TODO: This is an overly restrictive condition. It can be extended to: (Subquery is non-correlated || Subquery is correlated to any query outer to IN predicate || (Subquery is correlated to the immediate outer query && Subquery !contains {GROUP BY, ORDER BY [LIMIT], aggregate functions}) && subquery predicate is not under "NOT IN")) */ cause= "correlated"; } else { /* Check that involved expression types allow materialization. This is a temporary fix for BUG#36752; see bug report for description of restrictions we need to put on the compared expressions. */ DBUG_ASSERT(predicate->left_expr->fixed); // @see comment in Item_subselect::element_index() bool has_nullables= predicate->left_expr->maybe_null; List_iterator<Item> it(predicate->unit->first_select()->item_list); for (uint i= 0; i < elements; i++) { Item * const inner= it++; Item * const outer= predicate->left_expr->element_index(i); if (!types_allow_materialization(outer, inner)) { cause= "type mismatch"; break; } if (inner->is_blob_field()) // 6 { cause= "inner blob"; break; } has_nullables|= inner->maybe_null; } if (!cause) { trace_mat.add("has_nullable_expressions", has_nullables); /* Subquery materialization cannot handle NULLs partial matching properly, yet. If the outer or inner values are NULL, the subselect_hash_sj_engine may reply FALSE when it should reply UNKNOWN. So, we must limit it to those three cases: - when FALSE and UNKNOWN are equivalent answers. I.e. this is a a top-level predicate (this implies it is not negated). - when outer and inner values cannot be NULL. - when there is a single inner column (because for this we have a limited implementation of NULLs partial matching). */ const bool is_top_level= predicate->is_top_level_item(); trace_mat.add("treat_UNKNOWN_as_FALSE", is_top_level); if (!is_top_level && has_nullables && (elements > 1)) cause= "cannot_handle_partial_matches"; else { trace_mat.add("possible", true); DBUG_RETURN(TRUE); } } } DBUG_ASSERT(cause != NULL); trace_mat.add("possible", false).add_alnum("cause", cause); DBUG_RETURN(false); } /** Make list of leaf tables of join table tree @param list pointer to pointer on list first element @param tables table list @returns pointer on pointer to next_leaf of last element */ static TABLE_LIST **make_leaf_tables(TABLE_LIST **list, TABLE_LIST *tables) { for (TABLE_LIST *table= tables; table; table= table->next_local) { // A mergable view is not allowed to have a table pointer. DBUG_ASSERT(!(table->is_view() && table->is_merged() && table->table)); if (table->merge_underlying_list) { DBUG_ASSERT(table->is_merged()); list= make_leaf_tables(list, table->merge_underlying_list); } else { *list= table; list= &table->next_leaf; } } return list; } /** Check privileges for the view tables merged into a query block. @param thd Thread context. @param want_privilege_first Privileges requested for the first leaf. @param want_privilege_next Privileges requested for the remaining leaves. @note Beware that it can't properly check privileges in cases when table being changed is not the first table in the list of leaf tables (for example, for multi-UPDATE). @note The inner loop is slightly inefficient. A view will have its privileges checked once for every base table that it refers to. @returns false if success, true if error. */ bool st_select_lex::check_view_privileges(THD *thd, ulong want_privilege_first, ulong want_privilege_next) { ulong want_privilege= want_privilege_first; Internal_error_handler_holder<View_error_handler, TABLE_LIST> view_handler(thd, true, leaf_tables); for (TABLE_LIST *tl= leaf_tables; tl; tl= tl->next_leaf) { for (TABLE_LIST *ref= tl; ref->referencing_view; ref= ref->referencing_view) { if (check_single_table_access(thd, want_privilege, ref, false)) return true; } want_privilege= want_privilege_next; } return false; } /** Set up table leaves in the query block based on list of tables. @param thd Thread handler @param tables List of tables to handle @param select_insert It is SELECT ... INSERT command @note Check also that the 'used keys' and 'ignored keys' exists and set up the table structure accordingly. Create a list of leaf tables. This function has to be called for all tables that are used by items, as otherwise table->map is not set and all Item_field will be regarded as const items. @returns False on success, true on error */ bool st_select_lex::setup_tables(THD *thd, TABLE_LIST *tables, bool select_insert) { DBUG_ENTER("st_select_lex::setup_tables"); DBUG_ASSERT ((select_insert && !tables->next_name_resolution_table) || !tables || (context.table_list && context.first_name_resolution_table)); make_leaf_tables(&leaf_tables, tables); TABLE_LIST *first_select_table= NULL; if (select_insert) { // "insert_table" is needed for remap_tables(). thd->lex->insert_table= leaf_tables->top_table(); // Get first table in SELECT part first_select_table= thd->lex->insert_table->next_local; // Then, find the first leaf table if (first_select_table) first_select_table= first_select_table->first_leaf_table(); } uint tableno= 0; leaf_table_count= 0; partitioned_table_count= 0; Opt_hints_qb *qb_hints= context.select_lex->opt_hints_qb; for (TABLE_LIST *tr= leaf_tables; tr; tr= tr->next_leaf, tableno++) { TABLE *const table= tr->table; if (tr == first_select_table) { /* For INSERT ... SELECT command, restart numbering from zero for first leaf table from SELECT part of query. */ first_select_table= 0; tableno= 0; } if (tableno >= MAX_TABLES) { my_error(ER_TOO_MANY_TABLES,MYF(0), static_cast<int>(MAX_TABLES)); DBUG_RETURN(true); } tr->set_tableno(tableno); leaf_table_count++; // Count the input tables of the query if (table == NULL) continue; table->pos_in_table_list= tr; tr->reset(); if (qb_hints && // QB hints initialized !tr->opt_hints_table) // Table hints are not adjusted yet { tr->opt_hints_table= qb_hints->adjust_table_hints(table, tr->alias); } if (tr->process_index_hints(table)) DBUG_RETURN(true); if (table->part_info) // Count number of partitioned tables partitioned_table_count++; } if (qb_hints) qb_hints->check_unresolved(thd); DBUG_RETURN(false); } /** Re-map table numbers for all tables in a query block. @param thd Thread handler @note This function needs to be called after setup_tables() has been called, and after a query block for a subquery has been merged into a parent quary block. */ void st_select_lex::remap_tables(THD *thd) { LEX *const lex= thd->lex; TABLE_LIST *first_select_table= NULL; if (lex->insert_table && lex->insert_table == leaf_tables->top_table()) { /* For INSERT ... SELECT command, restart numbering from zero for first leaf table from SELECT part of query. */ // Get first table in SELECT part first_select_table= lex->insert_table->next_local; // Then, recurse down to get first leaf table if (first_select_table) first_select_table= first_select_table->first_leaf_table(); } uint tableno= 0; for (TABLE_LIST *tl= leaf_tables; tl; tl= tl->next_leaf) { // Reset table number after having reached first table after insert table if (first_select_table == tl) tableno= 0; tl->set_tableno(tableno++); } } /** @brief Resolve derived table and view references in query block @param thd Pointer to THD. @param apply_semijoin if true, apply semi-join transform when possible @return false if success, true if error */ bool st_select_lex::resolve_derived(THD *thd, bool apply_semijoin) { DBUG_ENTER("st_select_lex::resolve_derived"); DBUG_ASSERT(derived_table_count); materialized_derived_table_count= 0; // Prepare derived tables and views that belong to this query block. for (TABLE_LIST *tl= get_table_list(); tl; tl= tl->next_local) { if (!tl->is_view_or_derived() || tl->is_merged()) continue; if (tl->resolve_derived(thd, apply_semijoin)) DBUG_RETURN(true); } /* Merge the derived tables that do not require materialization into the current query block, if possible. Merging is only done once and must not be repeated for prepared execs. */ if (!(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW) && first_execution) { for (TABLE_LIST *tl= get_table_list(); tl; tl= tl->next_local) { if (!tl->is_view_or_derived() || tl->is_merged() || !tl->is_mergeable()) continue; if (merge_derived(thd, tl)) DBUG_RETURN(true); /* purecov: inspected */ } } // Prepare remaining derived tables for materialization for (TABLE_LIST *tl= get_table_list(); tl; tl= tl->next_local) { // Ensure that any derived table is merged or materialized after prepare: DBUG_ASSERT(first_execution || !tl->is_view_or_derived() || tl->is_merged() || tl->uses_materialization()); if (!tl->is_view_or_derived() || tl->is_merged()) continue; if (tl->setup_materialized_derived(thd)) DBUG_RETURN(true); materialized_derived_table_count++; } /* The loops above will not reach derived tables that are contained within other derived tables that have been merged into the enclosing query block. To reach them, traverse the list of leaf tables and resolve and setup for materialization those derived tables that have no TABLE object (they have not been set up yet). */ if (!first_execution) { for (TABLE_LIST *tl= leaf_tables; tl; tl= tl->next_leaf) { if (!tl->is_view_or_derived() || tl->table != NULL) continue; DBUG_ASSERT(!tl->is_merged()); if (tl->resolve_derived(thd, apply_semijoin)) DBUG_RETURN(true); /* purecov: inspected */ if (tl->setup_materialized_derived(thd)) DBUG_RETURN(true); /* purecov: inspected */ materialized_derived_table_count++; } } DBUG_RETURN(false); } /** @brief Resolve predicate involving subquery @param thd Pointer to THD. @retval FALSE Success. @retval TRUE Error. @details Perform early unconditional subquery transformations: - Convert subquery predicate into semi-join, or - Mark the subquery for execution using materialization, or - Perform IN->EXISTS transformation, or - Perform more/less ALL/ANY -> MIN/MAX rewrite - Substitute trivial scalar-context subquery with its value @todo for PS, make the whole block execute only on the first execution */ bool SELECT_LEX::resolve_subquery(THD *thd) { DBUG_ENTER("resolve_subquery"); bool chose_semijoin= false; SELECT_LEX *const outer= outer_select(); /* @todo for PS, make the whole block execute only on the first execution. resolve_subquery() is only invoked in the first execution for subqueries that are transformed to semijoin, but for other subqueries, this function is called for every execution. One solution is perhaps to define exec_method in class Item_subselect and exit immediately if unequal to EXEC_UNSPECIFIED. */ Item_subselect *subq_predicate= master_unit()->item; DBUG_ASSERT(subq_predicate); /** @note In this case: IN (SELECT ... UNION SELECT ...), SELECT_LEX::prepare() is called for each of the two UNION members, and in those two calls, subq_predicate is the same, not sure this is desired (double work?). */ Item_in_subselect * const in_predicate= (subq_predicate->substype() == Item_subselect::IN_SUBS) ? static_cast<Item_in_subselect *>(subq_predicate) : NULL; if (in_predicate) { thd->lex->set_current_select(outer); char const *save_where= thd->where; thd->where= "IN/ALL/ANY subquery"; Disable_semijoin_flattening DSF(outer, true); bool result= !in_predicate->left_expr->fixed && in_predicate->left_expr->fix_fields(thd, &in_predicate->left_expr); thd->lex->set_current_select(this); thd->where= save_where; if (result) DBUG_RETURN(true); /* Check if the left and right expressions have the same # of columns, i.e. we don't have a case like (oe1, oe2) IN (SELECT ie1, ie2, ie3 ...) TODO why do we have this duplicated in IN->EXISTS transformers? psergey-todo: fix these: grep for duplicated_subselect_card_check */ if (item_list.elements != in_predicate->left_expr->cols()) { my_error(ER_OPERAND_COLUMNS, MYF(0), in_predicate->left_expr->cols()); DBUG_RETURN(true); } } DBUG_PRINT("info", ("Checking if subq can be converted to semi-join")); /* Check if we're in subquery that is a candidate for flattening into a semi-join (which is done in flatten_subqueries()). The requirements are: 1. Subquery predicate is an IN/=ANY subquery predicate 2. Subquery is a single SELECT (not a UNION) 3. Subquery does not have GROUP BY 4. Subquery does not use aggregate functions or HAVING 5. Subquery predicate is (a) in an ON/WHERE clause, and (b) at the AND-top-level of that clause. 6. Parent query block accepts semijoins (i.e we are not in a subquery of a single table UPDATE/DELETE (TODO: We should handle this at some point by switching to multi-table UPDATE/DELETE) 7. We're not in a confluent table-less subquery, like "SELECT 1". 8. No execution method was already chosen (by a prepared statement) 9. Parent select is not a confluent table-less select 10. Neither parent nor child select have STRAIGHT_JOIN option. */ if (thd->optimizer_switch_flag(OPTIMIZER_SWITCH_SEMIJOIN) && in_predicate && // 1 !is_part_of_union() && // 2 !group_list.elements && // 3 !m_having_cond && !with_sum_func && // 4 (outer->resolve_place == st_select_lex::RESOLVE_CONDITION || // 5a outer->resolve_place == st_select_lex::RESOLVE_JOIN_NEST) && // 5a !outer->semijoin_disallowed && // 5b outer->sj_candidates && // 6 leaf_table_count && // 7 in_predicate->exec_method == Item_exists_subselect::EXEC_UNSPECIFIED && // 8 outer->leaf_table_count && // 9 !((active_options() | outer->active_options()) & SELECT_STRAIGHT_JOIN)) //10 { DBUG_PRINT("info", ("Subquery is semi-join conversion candidate")); /* Notify in the subquery predicate where it belongs in the query graph */ in_predicate->embedding_join_nest= outer->resolve_nest; /* Register the subquery for further processing in flatten_subqueries() */ outer->sj_candidates->push_back(in_predicate); chose_semijoin= true; } if (in_predicate) { Opt_trace_context * const trace= &thd->opt_trace; OPT_TRACE_TRANSFORM(trace, oto0, oto1, select_number, "IN (SELECT)", "semijoin"); oto1.add("chosen", chose_semijoin); } if (!chose_semijoin && subq_predicate->select_transformer(this) == Item_subselect::RES_ERROR) DBUG_RETURN(true); DBUG_RETURN(false); } /** Expand all '*' in list of expressions with the matching column references Function should not be called with no wild cards in select list @param thd thread handler @returns false if OK, true if error */ bool SELECT_LEX::setup_wild(THD *thd) { DBUG_ENTER("SELECT_LEX::setup_wild"); DBUG_ASSERT(with_wild); // PS/SP uses arena so that changes are made permanently. Prepared_stmt_arena_holder ps_arena_holder(thd); Item *item; List_iterator<Item> it(fields_list); while (with_wild && (item= it++)) { Item_field *item_field; if (item->type() == Item::FIELD_ITEM && (item_field= (Item_field *) item) && item_field->field_name && item_field->field_name[0] == '*' && !item_field->field) { const uint elem= fields_list.elements; const bool any_privileges= item_field->any_privileges; Item_subselect *subsel= master_unit()->item; if (subsel && subsel->substype() == Item_subselect::EXISTS_SUBS) { /* It is EXISTS(SELECT * ...) and we can replace * by any constant. Item_int do not need fix_fields() because it is basic constant. */ it.replace(new Item_int(NAME_STRING("Not_used"), (longlong) 1, MY_INT64_NUM_DECIMAL_DIGITS)); } else { if (insert_fields(thd, item_field->context, item_field->db_name, item_field->table_name, &it, any_privileges)) DBUG_RETURN(true); } /* all_fields is a list that has the fields list as a tail. Because of this we have to update the element count also for this list after expanding the '*' entry. */ all_fields.elements+= fields_list.elements - elem; with_wild--; } } DBUG_RETURN(false); } /** Resolve WHERE condition and join conditions @param thd thread handler @returns false if success, true if error */ bool SELECT_LEX::setup_conds(THD *thd) { DBUG_ENTER("SELECT_LEX::setup_conds"); /* it_is_update set to TRUE when tables of primary SELECT_LEX (SELECT_LEX which belong to LEX, i.e. most up SELECT) will be updated by INSERT/UPDATE/LOAD NOTE: using this condition helps to prevent call of prepare_check_option() from subquery of VIEW, because tables of subquery belongs to VIEW (see condition before prepare_check_option() call) */ const bool it_is_update= (this == thd->lex->select_lex) && thd->lex->which_check_option_applicable(); const bool save_is_item_list_lookup= is_item_list_lookup; is_item_list_lookup= false; DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns)); if (m_where_cond) { resolve_place= st_select_lex::RESOLVE_CONDITION; thd->where="where clause"; if ((!m_where_cond->fixed && m_where_cond->fix_fields(thd, &m_where_cond)) || m_where_cond->check_cols(1)) DBUG_RETURN(true); resolve_place= st_select_lex::RESOLVE_NONE; } /* Apply fix_fields() to all ON clauses at all levels of nesting, including the ones inside view definitions. */ for (TABLE_LIST *table= leaf_tables; table; table= table->next_leaf) { TABLE_LIST *embedded; /* The table at the current level of nesting. */ TABLE_LIST *embedding= table; /* The parent nested table reference. */ do { embedded= embedding; if (embedded->join_cond()) { resolve_place= st_select_lex::RESOLVE_JOIN_NEST; resolve_nest= embedded; thd->where="on clause"; if ((!embedded->join_cond()->fixed && embedded->join_cond()->fix_fields(thd, embedded->join_cond_ref())) || embedded->join_cond()->check_cols(1)) DBUG_RETURN(true); cond_count++; resolve_place= st_select_lex::RESOLVE_NONE; resolve_nest= NULL; } embedding= embedded->embedding; } while (embedding && embedding->nested_join->join_list.head() == embedded); /* process CHECK OPTION */ if (it_is_update) { TABLE_LIST *view= table->top_table(); if (view->effective_with_check) { if (view->prepare_check_option(thd)) DBUG_RETURN(true); /* purecov: inspected */ thd->change_item_tree(&table->check_option, view->check_option); } } } is_item_list_lookup= save_is_item_list_lookup; DBUG_ASSERT(thd->lex->current_select() == this); DBUG_ASSERT(!thd->is_error()); DBUG_RETURN(false); } /** Set NESTED_JOIN::counter=0 in all nested joins in passed list. @param join_list Pass NULL. Non-NULL is reserved for recursive inner calls, then it is a list of nested joins to process, and may also contain base tables which will be ignored. */ void SELECT_LEX::reset_nj_counters(List<TABLE_LIST> *join_list) { if (join_list == NULL) join_list= &top_join_list; List_iterator<TABLE_LIST> li(*join_list); TABLE_LIST *table; DBUG_ENTER("reset_nj_counters"); while ((table= li++)) { NESTED_JOIN *nested_join; if ((nested_join= table->nested_join)) { nested_join->nj_counter= 0; reset_nj_counters(&nested_join->join_list); } } DBUG_VOID_RETURN; } /** Simplify joins replacing outer joins by inner joins whenever it's possible. The function, during a retrieval of join_list, eliminates those outer joins that can be converted into inner join, possibly nested. It also moves the join conditions for the converted outer joins and from inner joins to conds. The function also calculates some attributes for nested joins: - used_tables - not_null_tables - dep_tables. - on_expr_dep_tables The first two attributes are used to test whether an outer join can be substituted for an inner join. The third attribute represents the relation 'to be dependent on' for tables. If table t2 is dependent on table t1, then in any evaluated execution plan table access to table t2 must precede access to table t2. This relation is used also to check whether the query contains invalid cross-references. The forth attribute is an auxiliary one and is used to calculate dep_tables. As the attribute dep_tables qualifies possibles orders of tables in the execution plan, the dependencies required by the straight join modifiers are reflected in this attribute as well. The function also removes all braces that can be removed from the join expression without changing its meaning. @note An outer join can be replaced by an inner join if the where condition or the join condition for an embedding nested join contains a conjunctive predicate rejecting null values for some attribute of the inner tables. E.g. in the query: @code SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t1.a WHERE t2.b < 5 @endcode the predicate t2.b < 5 rejects nulls. The query is converted first to: @code SELECT * FROM t1 INNER JOIN t2 ON t2.a=t1.a WHERE t2.b < 5 @endcode then to the equivalent form: @code SELECT * FROM t1, t2 ON t2.a=t1.a WHERE t2.b < 5 AND t2.a=t1.a @endcode Similarly the following query: @code SELECT * from t1 LEFT JOIN (t2, t3) ON t2.a=t1.a t3.b=t1.b WHERE t2.c < 5 @endcode is converted to: @code SELECT * FROM t1, (t2, t3) WHERE t2.c < 5 AND t2.a=t1.a t3.b=t1.b @endcode One conversion might trigger another: @code SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t1.a LEFT JOIN t3 ON t3.b=t2.b WHERE t3 IS NOT NULL => SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t1.a, t3 WHERE t3 IS NOT NULL AND t3.b=t2.b => SELECT * FROM t1, t2, t3 WHERE t3 IS NOT NULL AND t3.b=t2.b AND t2.a=t1.a @endcode The function removes all unnecessary braces from the expression produced by the conversions. E.g. @code SELECT * FROM t1, (t2, t3) WHERE t2.c < 5 AND t2.a=t1.a AND t3.b=t1.b @endcode finally is converted to: @code SELECT * FROM t1, t2, t3 WHERE t2.c < 5 AND t2.a=t1.a AND t3.b=t1.b @endcode It also will remove braces from the following queries: @code SELECT * from (t1 LEFT JOIN t2 ON t2.a=t1.a) LEFT JOIN t3 ON t3.b=t2.b SELECT * from (t1, (t2,t3)) WHERE t1.a=t2.a AND t2.b=t3.b. @endcode The benefit of this simplification procedure is that it might return a query for which the optimizer can evaluate execution plan with more join orders. With a left join operation the optimizer does not consider any plan where one of the inner tables is before some of outer tables. IMPLEMENTATION The function is implemented by a recursive procedure. On the recursive ascent all attributes are calculated, all outer joins that can be converted are replaced and then all unnecessary braces are removed. As join list contains join tables in the reverse order sequential elimination of outer joins does not require extra recursive calls. SEMI-JOIN NOTES Remove all semi-joins that have are within another semi-join (i.e. have an "ancestor" semi-join nest) EXAMPLES Here is an example of a join query with invalid cross references: @code SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t3.a LEFT JOIN t3 ON t3.b=t1.b @endcode @param thd thread handler @param join_list list representation of the join to be converted @param top true <=> cond is the where condition @param in_sj TRUE <=> processing semi-join nest's children @param[in,out] cond In: condition to which the join condition for converted outer joins is to be added; Out: new condition @param changelog Don't specify this parameter, it is reserved for recursive calls inside this function @returns true for error, false for success */ bool SELECT_LEX::simplify_joins(THD *thd, List<TABLE_LIST> *join_list, bool top, bool in_sj, Item **cond, uint *changelog) { /* Each type of change done by this function, or its recursive calls, is tracked in a bitmap: */ enum change { NONE= 0, OUTER_JOIN_TO_INNER= 1 << 0, JOIN_COND_TO_WHERE= 1 << 1, PAREN_REMOVAL= 1 << 2, SEMIJOIN= 1 << 3 }; uint changes= 0; // To keep track of changes. if (changelog == NULL) // This is the top call. changelog= &changes; TABLE_LIST *table; NESTED_JOIN *nested_join; TABLE_LIST *prev_table= 0; List_iterator<TABLE_LIST> li(*join_list); const bool straight_join= active_options() & SELECT_STRAIGHT_JOIN; DBUG_ENTER("simplify_joins"); /* Try to simplify join operations from join_list. The most outer join operation is checked for conversion first. */ while ((table= li++)) { table_map used_tables; table_map not_null_tables= (table_map) 0; if ((nested_join= table->nested_join)) { /* If the element of join_list is a nested join apply the procedure to its nested join list first. */ if (table->join_cond()) { Item *join_cond= table->join_cond(); /* If a join condition JC is attached to the table, check all null rejected predicates in this condition. If such a predicate over an attribute belonging to an inner table of an embedded outer join is found, the outer join is converted to an inner join and the corresponding join condition is added to JC. */ if (simplify_joins(thd, &nested_join->join_list, false, in_sj || table->sj_cond(), &join_cond, changelog)) DBUG_RETURN(true); if (join_cond != table->join_cond()) { DBUG_ASSERT(join_cond); table->set_join_cond(join_cond); } } nested_join->used_tables= (table_map) 0; nested_join->not_null_tables=(table_map) 0; if (simplify_joins(thd, &nested_join->join_list, top, in_sj || table->sj_cond(), cond, changelog)) DBUG_RETURN(true); used_tables= nested_join->used_tables; not_null_tables= nested_join->not_null_tables; } else { used_tables= table->map(); if (*cond) not_null_tables= (*cond)->not_null_tables(); } if (table->embedding) { table->embedding->nested_join->used_tables|= used_tables; table->embedding->nested_join->not_null_tables|= not_null_tables; } if (!table->outer_join || (used_tables & not_null_tables)) { /* For some of the inner tables there are conjunctive predicates that reject nulls => the outer join can be replaced by an inner join. */ if (table->outer_join) { *changelog|= OUTER_JOIN_TO_INNER; table->outer_join= 0; } if (table->join_cond()) { *changelog|= JOIN_COND_TO_WHERE; /* Add join condition to the WHERE or upper-level join condition. */ if (*cond) { Item_cond_and *new_cond= static_cast<Item_cond_and*>(and_conds(*cond, table->join_cond())); if (!new_cond) DBUG_RETURN(true); new_cond->top_level_item(); /* It is always a new item as both the upper-level condition and a join condition existed */ DBUG_ASSERT(!new_cond->fixed); if (new_cond->fix_fields(thd, NULL)) DBUG_RETURN(true); /* If join condition has a pending rollback in THD::change_list */ List_iterator<Item> lit(*new_cond->argument_list()); Item *arg; while ((arg= lit++)) { /* The join condition isn't necessarily the second argument anymore, since fix_fields may have merged it into an existing AND expr. */ if (arg == table->join_cond()) thd->change_item_tree_place(table->join_cond_ref(), lit.ref()); else if (arg == *cond) thd->change_item_tree_place(cond, lit.ref()); } *cond= new_cond; } else { *cond= table->join_cond(); /* If join condition has a pending rollback in THD::change_list */ thd->change_item_tree_place(table->join_cond_ref(), cond); } table->set_join_cond(NULL); } } if (!top) continue; /* Only inner tables of non-convertible outer joins remain with the join condition. */ if (table->join_cond()) { table->dep_tables|= table->join_cond()->used_tables(); // At this point the joined tables always have an embedding join nest: DBUG_ASSERT(table->embedding); table->dep_tables&= ~table->embedding->nested_join->used_tables; // Embedding table depends on tables used in embedded join conditions. table->embedding->on_expr_dep_tables|= table->join_cond()->used_tables(); } if (prev_table) { /* The order of tables is reverse: prev_table follows table */ if (prev_table->straight || straight_join) prev_table->dep_tables|= used_tables; if (prev_table->join_cond()) { prev_table->dep_tables|= table->on_expr_dep_tables; table_map prev_used_tables= prev_table->nested_join ? prev_table->nested_join->used_tables : prev_table->map(); /* If join condition contains only references to inner tables we still make the inner tables dependent on the outer tables. It would be enough to set dependency only on one outer table for them. Yet this is really a rare case. Note: PSEUDO_TABLE_BITS mask should not be counted as it prevents update of inner table dependencies. For example it might happen if RAND()/COUNT(*) function is used in JOIN ON clause. */ if (!((prev_table->join_cond()->used_tables() & ~PSEUDO_TABLE_BITS) & ~prev_used_tables)) prev_table->dep_tables|= used_tables; } } prev_table= table; } /* Flatten nested joins that can be flattened. no join condition and not a semi-join => can be flattened. */ li.rewind(); while ((table= li++)) { nested_join= table->nested_join; if (table->sj_cond() && !in_sj) { /* If this is a semi-join that is not contained within another semi-join, leave it intact (otherwise it is flattened) */ *changelog|= SEMIJOIN; } else if (nested_join && !table->join_cond()) { *changelog|= PAREN_REMOVAL; TABLE_LIST *tbl; List_iterator<TABLE_LIST> it(nested_join->join_list); while ((tbl= it++)) { tbl->embedding= table->embedding; tbl->join_list= table->join_list; tbl->dep_tables|= table->dep_tables; } li.replace(nested_join->join_list); } } if (changes) { Opt_trace_context * trace= &thd->opt_trace; if (unlikely(trace->is_started())) { Opt_trace_object trace_wrapper(trace); Opt_trace_object trace_object(trace, "transformations_to_nested_joins"); { Opt_trace_array trace_changes(trace, "transformations"); if (changes & SEMIJOIN) trace_changes.add_alnum("semijoin"); if (changes & OUTER_JOIN_TO_INNER) trace_changes.add_alnum("outer_join_to_inner_join"); if (changes & JOIN_COND_TO_WHERE) trace_changes.add_alnum("JOIN_condition_to_WHERE"); if (changes & PAREN_REMOVAL) trace_changes.add_alnum("parenthesis_removal"); } // the newly transformed query is worth printing opt_trace_print_expanded_query(thd, this, &trace_object); } } DBUG_RETURN(false); } /** Record join nest info in the select block. After simplification of inner join, outer join and semi-join structures: - record the remaining semi-join structures in the enclosing query block. - record transformed join conditions in TABLE_LIST objects. This function is called recursively for each join nest and/or table in the query block. @param select The query block @param tables List of tables and join nests @return False if successful, True if failure */ bool SELECT_LEX::record_join_nest_info(List<TABLE_LIST> *tables) { TABLE_LIST *table; List_iterator<TABLE_LIST> li(*tables); DBUG_ENTER("record_join_nest_info"); while ((table= li++)) { if (table->nested_join == NULL) { if (table->join_cond()) outer_join|= table->map(); continue; } if (record_join_nest_info(&table->nested_join->join_list)) DBUG_RETURN(true); /* sj_inner_tables is set properly later in pull_out_semijoin_tables(). This assignment is required in case pull_out_semijoin_tables() is not called. */ if (table->sj_cond()) table->sj_inner_tables= table->nested_join->used_tables; if (table->sj_cond() && sj_nests.push_back(table)) DBUG_RETURN(true); if (table->join_cond()) outer_join|= table->nested_join->used_tables; } DBUG_RETURN(false); } static int subq_sj_candidate_cmp(Item_exists_subselect* const *el1, Item_exists_subselect* const *el2) { /* Remove this assert when we support semijoin on non-IN subqueries. */ DBUG_ASSERT((*el1)->substype() == Item_subselect::IN_SUBS && (*el2)->substype() == Item_subselect::IN_SUBS); return ((*el1)->sj_convert_priority < (*el2)->sj_convert_priority) ? 1 : ( ((*el1)->sj_convert_priority == (*el2)->sj_convert_priority)? 0 : -1); } /** Update table reference information for conditions and expressions due to query blocks having been merged in from derived tables/views and due to semi-join transformation. This is needed for two reasons: 1. Since table numbers are changed, we need to update used_tables information for all conditions and expressions that are possibly touched. 2. For semi-join, some column references are changed from outer references to local references. The function needs to recursively walk down into join nests, in order to cover all conditions and expressions. For a semi-join, tables from the subquery are added last in the query block. This means that conditions and expressions from the outer query block are unaffected. But all conditions inside the semi-join nest, including join conditions, must have their table numbers changed. For a derived table/view, tables from the subquery are merged into the outer query, and this function is called for every derived table that is merged in. This algorithm only works when derived tables are merged in the order of their original table numbers. A hypothetical example with a triple self-join over a mergeable view: CREATE VIEW v AS SELECT t1.a, t2.b FROM t1 JOIN t2 USING (a); SELECT v1.a, v1.b, v2.b, v3.b FROM v AS v1 JOIN v AS v2 ON ... JOIN v AS v3 ON ...; The analysis starts with three tables v1, v2 and v3 having numbers 0, 1, 2. First we merge in v1, so we get (t1, t2, v2, v3). v2 and v3 are shifted up. Tables from v1 need to have their table numbers altered (actually they do not since both old and new numbers are 0 and 1, but this is a special case). v2 and v3 are not merged in yet, so we delay pullout on them until they are merged. Conditions and expressions from the outer query are not resolved yet, so regular resolving will take of them later. Then we merge in v2, so we get (t1, t2, t1, t2, v3). The tables from this view gets numbers 2 and 3, and v3 gets number 4. Because v2 had a higher number than the tables from v1, the join nest representing v1 is unaffected. And v3 is still not merged, so the only join nest we need to consider is v2. Finally we merge in v3, and then we have tables (t1, t2, t1, t2, t1, t2), with numbers 0 through 5. Again, since v3 has higher number than any of the already merged in views, only this join nest needs the pullout. @param parent_select Query block being merged into @param removed_select Query block that is removed (subquery) @param tr Table object this pullout is applied to @param table_adjust Number of positions that a derived table nest is adjusted, used to fix up semi-join related fields. Tables are adjusted from position N to N+table_adjust */ static void fix_tables_after_pullout(st_select_lex *parent_select, st_select_lex *removed_select, TABLE_LIST *tr, uint table_adjust) { if (tr->is_merged()) { // Update select list of merged derived tables: for (Field_translator *transl= tr->field_translation; transl < tr->field_translation_end; transl++) { DBUG_ASSERT(transl->item->fixed); transl->item->fix_after_pullout(parent_select, removed_select); } // Update used table info for the WHERE clause of the derived table DBUG_ASSERT(!tr->derived_where_cond || tr->derived_where_cond->fixed); if (tr->derived_where_cond) tr->derived_where_cond->fix_after_pullout(parent_select, removed_select); } /* If join_cond() is fixed, it contains a join condition from a subquery that has already been resolved. Call fix_after_pullout() to update used table information since table numbers may have changed. If join_cond() is not fixed, it contains a condition that was generated in the derived table merge operation, which will be fixed later. This condition may also contain a fixed part, but this is saved as derived_where_cond and is pulled out explicitly. */ if (tr->join_cond() && tr->join_cond()->fixed) tr->join_cond()->fix_after_pullout(parent_select, removed_select); if (tr->nested_join) { // In case a derived table is merged-in, these fields need adjustment: tr->nested_join->sj_corr_tables<<= table_adjust; tr->nested_join->sj_depends_on<<= table_adjust; List_iterator<TABLE_LIST> it(tr->nested_join->join_list); TABLE_LIST *child; while ((child= it++)) fix_tables_after_pullout(parent_select, removed_select, child, table_adjust); } } /** Convert a subquery predicate of this query block into a TABLE_LIST semi-join nest. @param subq_pred Subquery predicate to be converted. This is either an IN, =ANY or EXISTS predicate. @retval FALSE OK @retval TRUE Error @details The following transformations are performed: 1. IN/=ANY predicates on the form: SELECT ... FROM ot1 ... otN WHERE (oe1, ... oeM) IN (SELECT ie1, ..., ieM) FROM it1 ... itK [WHERE inner-cond]) [AND outer-cond] [GROUP BY ...] [HAVING ...] [ORDER BY ...] are transformed into: SELECT ... FROM (ot1 ... otN) SJ (it1 ... itK) ON (oe1, ... oeM) = (ie1, ..., ieM) [AND inner-cond] [WHERE outer-cond] [GROUP BY ...] [HAVING ...] [ORDER BY ...] Notice that the inner-cond may contain correlated and non-correlated expressions. Further transformations will analyze and break up such expressions. Prepared Statements: the transformation is permanent: - Changes in TABLE_LIST structures are naturally permanent - Item tree changes are performed on statement MEM_ROOT: = we activate statement MEM_ROOT = this function is called before the first fix_prepare_information call. This is intended because the criteria for subquery-to-sj conversion remain constant for the lifetime of the Prepared Statement. */ bool SELECT_LEX::convert_subquery_to_semijoin(Item_exists_subselect *subq_pred) { TABLE_LIST *emb_tbl_nest= NULL; List<TABLE_LIST> *emb_join_list= &top_join_list; THD *const thd= subq_pred->unit->thd; DBUG_ENTER("convert_subquery_to_semijoin"); DBUG_ASSERT(subq_pred->substype() == Item_subselect::IN_SUBS); bool outer_join= false; // True if predicate is inner to an outer join /* Find out where to insert the semi-join nest and the generated condition. For t1 LEFT JOIN t2, embedding_join_nest will be t2. Note that t2 may be a simple table or may itself be a join nest (e.g. in the case t1 LEFT JOIN (t2 JOIN t3)) */ if (subq_pred->embedding_join_nest != NULL) { // Is this on inner side of an outer join? outer_join= subq_pred->embedding_join_nest->is_inner_table_of_outer_join(); if (subq_pred->embedding_join_nest->nested_join) { /* We're dealing with ... [LEFT] JOIN ( ... ) ON (subquery AND condition) ... The sj-nest will be inserted into the brackets nest. */ emb_tbl_nest= subq_pred->embedding_join_nest; emb_join_list= &emb_tbl_nest->nested_join->join_list; } else if (!subq_pred->embedding_join_nest->outer_join) { /* We're dealing with ... INNER JOIN tblX ON (subquery AND condition) ... The sj-nest will be tblX's "sibling", i.e. another child of its parent. This is ok because tblX is joined as an inner join. */ emb_tbl_nest= subq_pred->embedding_join_nest->embedding; if (emb_tbl_nest) emb_join_list= &emb_tbl_nest->nested_join->join_list; } else if (!subq_pred->embedding_join_nest->nested_join) { TABLE_LIST *outer_tbl= subq_pred->embedding_join_nest; /* We're dealing with ... LEFT JOIN tbl ON (on_expr AND subq_pred) ... we'll need to convert it into: ... LEFT JOIN ( tbl SJ (subq_tables) ) ON (on_expr AND subq_pred) ... | | |<----- wrap_nest ---->| Q: other subqueries may be pointing to this element. What to do? A1: simple solution: copy *subq_pred->embedding_join_nest= *parent_nest. But we'll need to fix other pointers. A2: Another way: have TABLE_LIST::next_ptr so the following subqueries know the table has been nested. A3: changes in the TABLE_LIST::outer_join will make everything work automatically. */ TABLE_LIST *const wrap_nest= TABLE_LIST::new_nested_join(thd->mem_root, "(sj-wrap)", outer_tbl->embedding, outer_tbl->join_list, this); if (wrap_nest == NULL) DBUG_RETURN(true); wrap_nest->nested_join->join_list.push_back(outer_tbl); outer_tbl->embedding= wrap_nest; outer_tbl->join_list= &wrap_nest->nested_join->join_list; /* An important note, if this 'PREPARE stmt'. The FROM clause of the outer query now looks like CONCAT(original FROM clause of outer query, sj-nest). Given that the original FROM clause is reversed, this list is interpreted as "sj-nest is first". Thus, at a next execution, setup_natural_join_types() will decide that the name resolution context of the FROM clause should start at the first inner table in sj-nest. However, note that in the present function we do not change first_name_resolution_table (and friends) of sj-inner tables. So, at the next execution, name resolution for columns of outer-table columns is bound to fail (the first inner table does not have outer tables in its chain of resolution). Fortunately, Item_field::cached_table, which is set during resolution of 'PREPARE stmt', gives us the answer and avoids a failing search. */ /* wrap_nest will take place of outer_tbl, so move the outer join flag and join condition. */ wrap_nest->outer_join= outer_tbl->outer_join; outer_tbl->outer_join= 0; // There are item-rollback problems in this function: see bug#16926177 wrap_nest->set_join_cond(outer_tbl->join_cond()->real_item()); outer_tbl->set_join_cond(NULL); List_iterator<TABLE_LIST> li(*wrap_nest->join_list); TABLE_LIST *tbl; while ((tbl= li++)) { if (tbl == outer_tbl) { li.replace(wrap_nest); break; } } /* Ok now wrap_nest 'contains' outer_tbl and we're ready to add the semi-join nest into it */ emb_join_list= &wrap_nest->nested_join->join_list; emb_tbl_nest= wrap_nest; } } TABLE_LIST *const sj_nest= TABLE_LIST::new_nested_join(thd->mem_root, "(sj-nest)", emb_tbl_nest, emb_join_list, this); if (sj_nest == NULL) DBUG_RETURN(true); /* purecov: inspected */ NESTED_JOIN *const nested_join= sj_nest->nested_join; /* Nests do not participate in those 'chains', so: */ /* sj_nest->next_leaf= sj_nest->next_local= sj_nest->next_global == NULL*/ emb_join_list->push_back(sj_nest); /* Natural joins inside a semi-join nest were already processed when the subquery went through initial preparation. */ sj_nest->nested_join->natural_join_processed= true; /* nested_join->used_tables and nested_join->not_null_tables are initialized in simplify_joins(). */ st_select_lex *const subq_select= subq_pred->unit->first_select(); nested_join->query_block_id= subq_select->select_number; // Merge tables from underlying query block into this join nest if (sj_nest->merge_underlying_tables(subq_select)) DBUG_RETURN(true); /* purecov: inspected */ /* Add tables from subquery at end of leaf table chain. (This also means that table map for parent query block tables are unchanged) */ TABLE_LIST *tl; for (tl= leaf_tables; tl->next_leaf; tl= tl->next_leaf) {} tl->next_leaf= subq_select->leaf_tables; // Add tables from subquery at end of next_local chain. for (tl= get_table_list(); tl->next_local; tl= tl->next_local) {} tl->next_local= subq_select->get_table_list(); // Note that subquery's tables are already in the next_global chain // Remove the original subquery predicate from the WHERE/ON // The subqueries were replaced for Item_int(1) earlier // @todo also reset the 'with_subselect' there. // Walk through child's tables and adjust table map uint table_no= leaf_table_count; for (tl= subq_select->leaf_tables; tl; tl= tl->next_leaf, table_no++) tl->set_tableno(table_no); // Adjust table and expression counts in parent query block: derived_table_count+= subq_select->derived_table_count; materialized_derived_table_count+= subq_select->materialized_derived_table_count; has_sj_nests|= subq_select->has_sj_nests; partitioned_table_count+= subq_select->partitioned_table_count; leaf_table_count+= subq_select->leaf_table_count; cond_count+= subq_select->cond_count; between_count+= subq_select->between_count; if (outer_join) propagate_nullability(&sj_nest->nested_join->join_list, true); nested_join->sj_outer_exprs.empty(); nested_join->sj_inner_exprs.empty(); /* @todo: Add similar conversion for subqueries other than IN. */ if (subq_pred->substype() == Item_subselect::IN_SUBS) { Item_in_subselect *in_subq_pred= (Item_in_subselect *)subq_pred; DBUG_ASSERT(is_fixed_or_outer_ref(in_subq_pred->left_expr)); in_subq_pred->exec_method= Item_exists_subselect::EXEC_SEMI_JOIN; /* sj_corr_tables is supposed to contain non-trivially correlated tables, but here it is set to contain all correlated tables. @todo: Add analysis step that assigns only the set of non-trivially correlated tables to sj_corr_tables. */ nested_join->sj_corr_tables= subq_pred->used_tables(); /* sj_depends_on contains the set of outer tables referred in the subquery's WHERE clause as well as tables referred in the IN predicate's left-hand side. */ nested_join->sj_depends_on= subq_pred->used_tables() | in_subq_pred->left_expr->used_tables(); // Put the subquery's WHERE into semi-join's condition. Item *sj_cond= subq_select->where_cond(); /* Create the IN-equalities and inject them into semi-join's ON condition. Additionally, for LooseScan strategy - Record the number of IN-equalities. - Create list of pointers to (oe1, ..., ieN). We'll need the list to see which of the expressions are bound and which are not (for those we'll produce a distinct stream of (ie_i1,...ie_ik). (TODO: can we just create a list of pointers and hope the expressions will not substitute themselves on fix_fields()? or we need to wrap them into Item_direct_view_refs and store pointers to those. The pointers to Item_direct_view_refs are guaranteed to be stable as Item_direct_view_refs doesn't substitute itself with anything in Item_direct_view_ref::fix_fields. We have a special case for IN predicates with a scalar subquery or a row subquery in the predicand (left operand), such as this: (SELECT 1,2 FROM t1) IN (SELECT x,y FROM t2) We cannot make the join condition 1=x AND 2=y, since that might evaluate to TRUE even if t1 is empty. Instead make the join condition (SELECT 1,2 FROM t1) = (x,y) in this case. */ Item_subselect *left_subquery= (in_subq_pred->left_expr->type() == Item::SUBSELECT_ITEM) ? static_cast<Item_subselect *>(in_subq_pred->left_expr) : NULL; if (left_subquery && (left_subquery->substype() == Item_subselect::SINGLEROW_SUBS)) { List<Item> ref_list; Item *header= subq_select->ref_pointer_array[0]; for (uint i= 1; i < in_subq_pred->left_expr->cols(); i++) { ref_list.push_back(subq_select->ref_pointer_array[i]); } Item_row *right_expr= new Item_row(header, ref_list); if (!right_expr) DBUG_RETURN(true); /* purecov: inspected */ nested_join->sj_outer_exprs.push_back(in_subq_pred->left_expr); nested_join->sj_inner_exprs.push_back(right_expr); Item_func_eq *item_eq= new Item_func_eq(in_subq_pred->left_expr, right_expr); if (item_eq == NULL) DBUG_RETURN(true); /* purecov: inspected */ sj_cond= and_items(sj_cond, item_eq); if (sj_cond == NULL) DBUG_RETURN(true); /* purecov: inspected */ } else { for (uint i= 0; i < in_subq_pred->left_expr->cols(); i++) { nested_join->sj_outer_exprs.push_back(in_subq_pred->left_expr-> element_index(i)); nested_join->sj_inner_exprs.push_back(subq_select->ref_pointer_array[i]); Item_func_eq *item_eq= new Item_func_eq(in_subq_pred->left_expr->element_index(i), subq_select->ref_pointer_array[i]); if (item_eq == NULL) DBUG_RETURN(true); /* purecov: inspected */ sj_cond= and_items(sj_cond, item_eq); if (sj_cond == NULL) DBUG_RETURN(true); /* purecov: inspected */ } } // Fix the created equality and AND Opt_trace_array sj_on_trace(&thd->opt_trace, "evaluating_constant_semijoin_conditions"); sj_cond->top_level_item(); if (sj_cond->fix_fields(thd, &sj_cond)) DBUG_RETURN(true); /* purecov: inspected */ // Attach semi-join condition to semi-join nest sj_nest->set_sj_cond(sj_cond); } // Unlink the subquery's query expression: subq_select->master_unit()->exclude_level(); /* Add Name res objects belonging to subquery to parent query block. Update all name res objects to have this base query block. */ for (Name_resolution_context *ctx= subq_select->first_context; ctx != NULL; ctx= ctx->next_context) { ctx->select_lex= this; if (ctx->next_context == NULL) { ctx->next_context= first_context; first_context= subq_select->first_context; subq_select->first_context= NULL; break; } } repoint_contexts_of_join_nests(subq_select->top_join_list); // Update table map for the semi-join condition sj_nest->sj_cond()->fix_after_pullout(this, subq_select); // Update table map for semi-join nest's WHERE condition and join conditions fix_tables_after_pullout(this, subq_select, sj_nest, 0); //TODO fix QT_ DBUG_EXECUTE("where", print_where(sj_nest->sj_cond(),"SJ-COND", QT_ORDINARY);); if (emb_tbl_nest) { // Inject semi-join condition into parent's join condition emb_tbl_nest->set_join_cond(and_items(emb_tbl_nest->join_cond(), sj_nest->sj_cond())); if (emb_tbl_nest->join_cond() == NULL) DBUG_RETURN(true); emb_tbl_nest->join_cond()->top_level_item(); if (!emb_tbl_nest->join_cond()->fixed && emb_tbl_nest->join_cond()->fix_fields(thd, emb_tbl_nest->join_cond_ref())) DBUG_RETURN(true); } else { // Inject semi-join condition into parent's WHERE condition m_where_cond= and_items(m_where_cond, sj_nest->sj_cond()); if (m_where_cond == NULL) DBUG_RETURN(true); m_where_cond->top_level_item(); if (m_where_cond->fix_fields(thd, &m_where_cond)) DBUG_RETURN(true); } if (subq_select->ftfunc_list->elements && add_ftfunc_list(subq_select->ftfunc_list)) DBUG_RETURN(true); /* purecov: inspected */ // This query block has semi-join nests has_sj_nests= true; DBUG_RETURN(false); } /** Merge a derived table or view into a query block. If some constraint prevents the derived table from being merged then do nothing, which means the table will be prepared for materialization later. After this call, check is_merged() to see if the table was really merged. @param thd Thread handler @param derived_table Derived table which is to be merged. @return false if successful, true if error */ bool SELECT_LEX::merge_derived(THD *thd, TABLE_LIST *derived_table) { DBUG_ENTER("SELECT_LEX::merge_derived"); if (!derived_table->is_view_or_derived() || derived_table->is_merged()) DBUG_RETURN(false); SELECT_LEX_UNIT *const derived_unit= derived_table->derived_unit(); // A derived table must be prepared before we can merge it DBUG_ASSERT(derived_unit->is_prepared()); LEX *const lex= parent_lex; // Check whether the outer query allows merged views if ((master_unit() == lex->unit && !lex->can_use_merged()) || lex->can_not_use_merged()) DBUG_RETURN(false); // Check whether derived table is mergeable, and directives allow merging if (!derived_unit->is_mergeable() || derived_table->algorithm == VIEW_ALGORITHM_TEMPTABLE || (!thd->optimizer_switch_flag(OPTIMIZER_SWITCH_DERIVED_MERGE) && derived_table->algorithm != VIEW_ALGORITHM_MERGE)) DBUG_RETURN(false); SELECT_LEX *const derived_select= derived_unit->first_select(); /* If STRAIGHT_JOIN is specified, it is not valid to merge in a query block that contains semi-join nests */ if ((active_options() & SELECT_STRAIGHT_JOIN) && derived_select->has_sj_nests) DBUG_RETURN(false); // Check that we have room for the merged tables in the table map: if (leaf_table_count + derived_select->leaf_table_count - 1 > MAX_TABLES) DBUG_RETURN(false); derived_table->set_merged(); DBUG_PRINT("info", ("algorithm: MERGE")); Opt_trace_context *const trace= &thd->opt_trace; Opt_trace_object trace_wrapper(trace); Opt_trace_object trace_derived(trace, derived_table->is_view() ? "view" : "derived"); trace_derived.add_utf8_table(derived_table). add("select#", derived_select->select_number). add("merged", true); Prepared_stmt_arena_holder ps_arena_holder(thd); // Save offset for table number adjustment uint table_adjust= derived_table->tableno(); // Set up permanent list of underlying tables of a merged view derived_table->merge_underlying_list= derived_select->get_table_list(); if (derived_table->updatable_view && (derived_table->merge_underlying_list == NULL || derived_table->merge_underlying_list->is_updatable())) derived_table->set_updatable(); derived_table->effective_with_check= lex->get_effective_with_check(derived_table); // Add a nested join object to the derived table object if (!(derived_table->nested_join= (NESTED_JOIN *) thd->mem_calloc(sizeof(NESTED_JOIN)))) DBUG_RETURN(true); /* purecov: inspected */ derived_table->nested_join->join_list.empty();//Should be done by constructor! // Merge tables from underlying query block into this join nest if (derived_table->merge_underlying_tables(derived_select)) DBUG_RETURN(true); /* purecov: inspected */ // Replace derived table in leaf table list with underlying tables: for (TABLE_LIST **tl= &leaf_tables; *tl; tl= &(*tl)->next_leaf) { if (*tl == derived_table) { for (TABLE_LIST *leaf= derived_select->leaf_tables; leaf; leaf= leaf->next_leaf) { if (leaf->next_leaf == NULL) { leaf->next_leaf= (*tl)->next_leaf; break; } } *tl= derived_select->leaf_tables; break; } } leaf_table_count+= (derived_select->leaf_table_count - 1); derived_table_count+= derived_select->derived_table_count; materialized_derived_table_count+= derived_select->materialized_derived_table_count; has_sj_nests|= derived_select->has_sj_nests; partitioned_table_count+= derived_select->partitioned_table_count; cond_count+= derived_select->cond_count; between_count+= derived_select->between_count; // Propagate schema table indication: // @todo: Add to BASE options instead if (derived_select->active_options() & OPTION_SCHEMA_TABLE) add_base_options(OPTION_SCHEMA_TABLE); // Propagate nullability for derived tables within outer joins: if (derived_table->is_inner_table_of_outer_join()) propagate_nullability(&derived_table->nested_join->join_list, true); select_n_having_items+= derived_select->select_n_having_items; // Merge the WHERE clause into the outer query block if (derived_table->merge_where(thd)) DBUG_RETURN(true); /* purecov: inspected */ if (derived_table->create_field_translation(thd)) DBUG_RETURN(true); /* purecov: inspected */ // Exclude the derived table query expression from query graph. derived_unit->exclude_level(); // Don't try to access it: derived_table->set_derived_unit((SELECT_LEX_UNIT *)1); /* Add Name res objects belonging to subquery to parent query block. Update all name res objects to have this base query block. */ for (Name_resolution_context *ctx= derived_select->first_context; ctx != NULL; ctx= ctx->next_context) { ctx->select_lex= this; if (ctx->next_context == NULL) { ctx->next_context= first_context; first_context= derived_select->first_context; derived_select->first_context= NULL; break; } } repoint_contexts_of_join_nests(derived_select->top_join_list); // Leaf tables have been shuffled, so update table numbers for them remap_tables(thd); // Update table info of referenced expressions after query block is merged fix_tables_after_pullout(this, derived_select, derived_table, table_adjust); if (derived_select->is_ordered()) { /* An ORDER BY clause is moved to an outer query block - if the outer query block allows ordering, and - that refers to this view/derived table only, and - is not part of a UNION, and - may have a WHERE clause but is not grouped or aggregated and is not itself ordered. Otherwise the ORDER BY clause is ignored. Up to version 5.6 included, ORDER BY was unconditionally merged. Currently we only merge in the simple case above, which ensures backward compatibility for most reasonable use cases. Note that table numbers in order_list do not need updating, since the outer query contains only one table reference. */ // LIMIT currently blocks derived table merge DBUG_ASSERT(!derived_select->has_limit()); if (!(master_unit()->is_union() || lex->sql_command == SQLCOM_UPDATE_MULTI || lex->sql_command == SQLCOM_DELETE_MULTI || is_grouped() || is_distinct() || is_ordered() || get_table_list()->next_local != NULL)) order_list.push_back(&derived_select->order_list); } // Add any full-text functions from derived table into outer query if (derived_select->ftfunc_list->elements && add_ftfunc_list(derived_select->ftfunc_list)) DBUG_RETURN(true); /* purecov: inspected */ DBUG_RETURN(false); } /** Destructively replaces a sub-condition inside a condition tree. The parse tree is also altered. @note Because of current requirements for semijoin flattening, we do not need to recurse here, hence this function will only examine the top-level AND conditions. (see SELECT_LEX::prepare, comment starting with "Check if the subquery predicate can be executed via materialization".) @param thd thread handler @param tree Must be the handle to the top level condition. This is needed when the top-level condition changes. @param old_cond The condition to be replaced. @param new_cond The condition to be substituted. @param do_fix_fields If true, Item::fix_fields(THD*, Item**) is called for the new condition. @return error status @retval true If there was an error. @retval false If successful. */ static bool replace_subcondition(THD *thd, Item **tree, Item *old_cond, Item *new_cond, bool do_fix_fields) { if (*tree == old_cond) { *tree= new_cond; if (do_fix_fields && new_cond->fix_fields(thd, tree)) return TRUE; return FALSE; } else if ((*tree)->type() == Item::COND_ITEM) { List_iterator<Item> li(*((Item_cond*)(*tree))->argument_list()); Item *item; while ((item= li++)) { if (item == old_cond) { li.replace(new_cond); if (do_fix_fields && new_cond->fix_fields(thd, li.ref())) return TRUE; return FALSE; } } } else // If we came here it means there were an error during prerequisites check. DBUG_ASSERT(FALSE); return TRUE; } /* Convert semi-join subquery predicates into semi-join join nests DESCRIPTION Convert candidate subquery predicates into semi-join join nests. This transformation is performed once in query lifetime and is irreversible. Conversion of one subquery predicate ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We start with a join that has a semi-join subquery: SELECT ... FROM ot, ... WHERE oe IN (SELECT ie FROM it1 ... itN WHERE subq_where) AND outer_where and convert it into a semi-join nest: SELECT ... FROM ot SEMI JOIN (it1 ... itN), ... WHERE outer_where AND subq_where AND oe=ie that is, in order to do the conversion, we need to * Create the "SEMI JOIN (it1 .. itN)" part and add it into the parent query's FROM structure. * Add "AND subq_where AND oe=ie" into parent query's WHERE (or ON if the subquery predicate was in an ON expression) * Remove the subquery predicate from the parent query's WHERE Considerations when converting many predicates ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A join may have at most MAX_TABLES tables. This may prevent us from flattening all subqueries when the total number of tables in parent and child selects exceeds MAX_TABLES. In addition, one slot is reserved per semi-join nest, in case the subquery needs to be materialized in a temporary table. We deal with this problem by flattening children's subqueries first and then using a heuristic rule to determine each subquery predicate's "priority". RETURN FALSE OK TRUE Error */ bool SELECT_LEX::flatten_subqueries() { DBUG_ENTER("flatten_subqueries"); if (sj_candidates->empty()) DBUG_RETURN(FALSE); Item_exists_subselect **subq, **subq_begin= sj_candidates->begin(), **subq_end= sj_candidates->end(); THD *const thd= (*subq_begin)->unit->thd; Opt_trace_context *const trace= &thd->opt_trace; /* Semijoin flattening is bottom-up. Indeed, we have this execution flow, for SELECT#1 WHERE X IN (SELECT #2 WHERE Y IN (SELECT#3)) : SELECT_LEX::prepare() (select#1) -> fix_fields() on IN condition -> SELECT_LEX::prepare() on subquery (select#2) -> fix_fields() on IN condition -> SELECT_LEX::prepare() on subquery (select#3) <- SELECT_LEX::prepare() <- fix_fields() -> flatten_subqueries: merge #3 in #2 <- flatten_subqueries <- SELECT_LEX::prepare() <- fix_fields() -> flatten_subqueries: merge #2 in #1 Note that flattening of #(N) is done by its parent JOIN#(N-1), because there are cases where flattening is not possible and only the parent can know. */ for (subq= subq_begin; subq < subq_end; subq++) { /* Currently, we only support transformation of IN subqueries. */ DBUG_ASSERT((*subq)->substype() == Item_subselect::IN_SUBS); st_select_lex *child_select= (*subq)->unit->first_select(); // Check that we proceeded bottom-up DBUG_ASSERT(child_select->sj_candidates == NULL); (*subq)->sj_convert_priority= (((*subq)->unit->uncacheable & UNCACHEABLE_DEPENDENT) ? MAX_TABLES : 0) + child_select->leaf_table_count; } /* 2. Pick which subqueries to convert: sort the subquery array - prefer correlated subqueries over uncorrelated; - prefer subqueries that have greater number of outer tables; */ my_qsort(subq_begin, sj_candidates->size(), sj_candidates->element_size(), reinterpret_cast<qsort_cmp>(subq_sj_candidate_cmp)); // A permanent transformation is going to start, so: Prepared_stmt_arena_holder ps_arena_holder(thd); // #tables-in-parent-query + #tables-in-subquery + sj nests <= MAX_TABLES /* Replace all subqueries to be flattened with Item_int(1) */ uint table_count= leaf_table_count; for (subq= subq_begin; subq < subq_end; subq++) { // Add the tables in the subquery nest plus one in case of materialization: const uint tables_added= (*subq)->unit->first_select()->leaf_table_count + 1; (*subq)->sj_chosen= table_count + tables_added <= MAX_TABLES; if (!(*subq)->sj_chosen) continue; table_count+= tables_added; // In WHERE/ON of parent query, replace IN(subq) with "1" (<=>TRUE) Item **tree= ((*subq)->embedding_join_nest == NULL) ? &m_where_cond : (*subq)->embedding_join_nest->join_cond_ref(); if (replace_subcondition(thd, tree, *subq, new Item_int(1), FALSE)) DBUG_RETURN(TRUE); /* purecov: inspected */ } for (subq= subq_begin; subq < subq_end; subq++) { if (!(*subq)->sj_chosen) continue; OPT_TRACE_TRANSFORM(trace, oto0, oto1, (*subq)->unit->first_select()->select_number, "IN (SELECT)", "semijoin"); oto1.add("chosen", true); if (convert_subquery_to_semijoin(*subq)) DBUG_RETURN(TRUE); } /* 3. Finalize the subqueries that we did not convert, ie. perform IN->EXISTS rewrite. */ for (subq= subq_begin; subq < subq_end; subq++) { if ((*subq)->sj_chosen) continue; { OPT_TRACE_TRANSFORM(trace, oto0, oto1, (*subq)->unit->first_select()->select_number, "IN (SELECT)", "semijoin"); oto1.add("chosen", false); } Item_subselect::trans_res res; (*subq)->changed= 0; (*subq)->fixed= 0; SELECT_LEX *save_select_lex= thd->lex->current_select(); thd->lex->set_current_select((*subq)->unit->first_select()); // This is the only part of the function which uses a JOIN. res= (*subq)->select_transformer((*subq)->unit->first_select()); thd->lex->set_current_select(save_select_lex); if (res == Item_subselect::RES_ERROR) DBUG_RETURN(TRUE); (*subq)->changed= 1; (*subq)->fixed= 1; Item *substitute= (*subq)->substitution; const bool do_fix_fields= !(*subq)->substitution->fixed; const bool subquery_in_join_clause= (*subq)->embedding_join_nest != NULL; Item **tree= subquery_in_join_clause ? ((*subq)->embedding_join_nest->join_cond_ref()) : &m_where_cond; if (replace_subcondition(thd, tree, *subq, substitute, do_fix_fields)) DBUG_RETURN(TRUE); (*subq)->substitution= NULL; } sj_candidates->clear(); DBUG_RETURN(FALSE); } /** Propagate nullability into inner tables of outer join operation @param tables: List of tables and join nests, start at top_join_list @param nullable: true: Set all underlying tables as nullable */ static void propagate_nullability(List<TABLE_LIST> *tables, bool nullable) { List_iterator<TABLE_LIST> li(*tables); TABLE_LIST *tr; while ((tr= li++)) { if (tr->table && !tr->table->is_nullable() && (nullable || tr->outer_join)) tr->table->set_nullable(); if (tr->nested_join == NULL) continue; propagate_nullability(&tr->nested_join->join_list, nullable || tr->outer_join); } } /** Propagate exclusion from unique table check into all subqueries belonging to this query block. This function can be applied to all subqueries of a materialized derived table or view. */ void st_select_lex::propagate_unique_test_exclusion() { for (SELECT_LEX_UNIT *unit= first_inner_unit(); unit; unit= unit->next_unit()) for (SELECT_LEX *sl= unit->first_select(); sl; sl= sl->next_select()) sl->propagate_unique_test_exclusion(); exclude_from_table_unique_test= true; } /** Add a list of full-text function elements into a query block. @param ftfuncs List of full-text function elements to add. @returns false if success, true if error */ bool SELECT_LEX::add_ftfunc_list(List<Item_func_match> *ftfuncs) { Item_func_match *ifm; List_iterator_fast<Item_func_match> li(*ftfuncs); while ((ifm= li++)) { if (ftfunc_list->push_front(ifm)) return true; /* purecov: inspected */ } return false; } /** Go through a list of tables and join nests, recursively, and repoint its select_lex pointer. @param join_list List of tables and join nests */ void SELECT_LEX::repoint_contexts_of_join_nests(List<TABLE_LIST> join_list) { List_iterator_fast<TABLE_LIST> ti(join_list); TABLE_LIST *tbl; while ((tbl= ti++)) { tbl->select_lex= this; if (tbl->nested_join) repoint_contexts_of_join_nests(tbl->nested_join->join_list); } } /** Fix fields referenced from inner query blocks. @param thd Thread handle @details The function serves 3 purposes - adds fields referenced from inner query blocks to the current select list - Decides which class to use to reference the items (Item_ref or Item_direct_ref) - fixes references (Item_ref objects) to these fields. If a field isn't already on the select list and the ref_ptrs array is provided then it is added to the all_fields list and the pointer to it is saved in the ref_ptrs array. The class to access the outer field is determined by the following rules: -#. If the outer field isn't used under an aggregate function then the Item_ref class should be used. -#. If the outer field is used under an aggregate function and this function is, in turn, aggregated in the query block where the outer field was resolved or some query nested therein, then the Item_direct_ref class should be used. Also it should be used if we are grouping by a subquery containing the outer field. The resolution is done here and not at the fix_fields() stage as it can be done only after aggregate functions are fixed and pulled up to selects where they are to be aggregated. When the class is chosen it substitutes the original field in the Item_outer_ref object. After this we proceed with fixing references (Item_outer_ref objects) to this field from inner subqueries. @return false if success, true if error */ bool SELECT_LEX::fix_inner_refs(THD *thd) { Item_outer_ref *ref; List_iterator<Item_outer_ref> ref_it(inner_refs_list); while ((ref= ref_it++)) { bool direct_ref= false; Item *item= ref->outer_ref; Item **item_ref= ref->ref; /* TODO: this field item already might be present in the select list. In this case instead of adding new field item we could use an existing one. The change will lead to less operations for copying fields, smaller temporary tables and less data passed through filesort. */ if (!ref_ptrs.is_null() && !ref->found_in_select_list) { int el= all_fields.elements; ref_ptrs[el]= item; /* Add the field item to the select list of the current select. */ all_fields.push_front(item); /* If it's needed reset each Item_ref item that refers this field with a new reference taken from ref_pointer_array. */ item_ref= &ref_ptrs[el]; } if (ref->in_sum_func) { if (ref->in_sum_func->nest_level > nest_level) direct_ref= true; else { for (Item_sum *sum_func= ref->in_sum_func; sum_func && sum_func->aggr_level >= nest_level; sum_func= sum_func->in_sum_func) { if (sum_func->aggr_level == nest_level) { direct_ref= true; break; } } } } else { /* Check if GROUP BY item trees contain the outer ref: in this case we have to use Item_direct_ref instead of Item_ref. */ for (ORDER *group= group_list.first; group; group= group->next) { if ((*group->item)->walk(&Item::find_item_processor, walk_subquery, (uchar *) ref)) { direct_ref= true; break; } } } Item_ref *const new_ref= direct_ref ? new Item_direct_ref(ref->context, item_ref, ref->table_name, ref->field_name, ref->is_alias_of_expr()) : new Item_ref(ref->context, item_ref, ref->table_name, ref->field_name, ref->is_alias_of_expr()); if (!new_ref) return true; /* purecov: inspected */ ref->outer_ref= new_ref; ref->ref= &ref->outer_ref; if (!ref->fixed && ref->fix_fields(thd, 0)) return true; /* purecov: inspected */ thd->lex->used_tables|= item->used_tables(); select_list_tables|= item->used_tables(); } return false; } /** Since LIMIT is not supported for table subquery predicates (IN/ALL/EXISTS/etc), the following clauses are redundant for subqueries: ORDER BY DISTINCT GROUP BY if there are no aggregate functions and no HAVING clause This removal is permanent. Thus, it only makes sense to call this function for regular queries and on first execution of SP/PS @param thd thread handler @param hidden_group_field_count Number of hidden group fields added by setup_group(). @param hidden_order_field_count Number of hidden order fields added by setup_order(). */ void SELECT_LEX::remove_redundant_subquery_clauses(THD *thd, int hidden_group_field_count, int hidden_order_field_count) { Item_subselect *subq_predicate= master_unit()->item; /* The removal should happen for IN, ALL, ANY and EXISTS subqueries, which means all but single row subqueries. Example single row subqueries: a) SELECT * FROM t1 WHERE t1.a = (<single row subquery>) b) SELECT a, (<single row subquery) FROM t1 */ if (subq_predicate->substype() == Item_subselect::SINGLEROW_SUBS) return; // A subquery that is not single row should be one of IN/ALL/ANY/EXISTS. DBUG_ASSERT (subq_predicate->substype() == Item_subselect::EXISTS_SUBS || subq_predicate->substype() == Item_subselect::IN_SUBS || subq_predicate->substype() == Item_subselect::ALL_SUBS || subq_predicate->substype() == Item_subselect::ANY_SUBS); enum change { REMOVE_NONE=0, REMOVE_ORDER= 1 << 0, REMOVE_DISTINCT= 1 << 1, REMOVE_GROUP= 1 << 2 }; uint changelog= 0; if (order_list.elements) { changelog|= REMOVE_ORDER; empty_order_list(hidden_order_field_count); } if (is_distinct()) { changelog|= REMOVE_DISTINCT; remove_base_options(SELECT_DISTINCT); } // Remove GROUP BY if there are no aggregate functions and no HAVING clause if (group_list.elements && !agg_func_used() && !having_cond()) { changelog|= REMOVE_GROUP; for (ORDER *g= group_list.first; g != NULL; g= g->next) { if (*g->item == g->item_ptr) (*g->item)->walk(&Item::clean_up_after_removal, walk_subquery, reinterpret_cast<uchar*>(this)); } group_list.empty(); while (hidden_group_field_count-- > 0) { all_fields.pop(); ref_ptrs[all_fields.elements]= NULL; } } if (changelog) { Opt_trace_context * trace= &thd->opt_trace; if (unlikely(trace->is_started())) { Opt_trace_object trace_wrapper(trace); Opt_trace_array trace_changes(trace, "transformations_to_subquery"); if (changelog & REMOVE_ORDER) trace_changes.add_alnum("removed_ordering"); if (changelog & REMOVE_DISTINCT) trace_changes.add_alnum("removed_distinct"); if (changelog & REMOVE_GROUP) trace_changes.add_alnum("removed_grouping"); } } } /** Empty the ORDER list. Delete corresponding elements from all_fields and ref_ptrs too. If ORDER list contain any subqueries, delete them from the query block list. @param hidden_order_field_count Number of hidden order fields to remove */ void SELECT_LEX::empty_order_list(int hidden_order_field_count) { for (ORDER *o= order_list.first; o != NULL; o= o->next) { if (*o->item == o->item_ptr) (*o->item)->walk(&Item::clean_up_after_removal, walk_subquery, reinterpret_cast<uchar*>(this)); } order_list.empty(); while (hidden_order_field_count-- > 0) { all_fields.pop(); ref_ptrs[all_fields.elements]= NULL; } } /***************************************************************************** Group and order functions *****************************************************************************/ /** Resolve an ORDER BY or GROUP BY column reference. Given a column reference (represented by 'order') from a GROUP BY or ORDER BY clause, find the actual column it represents. If the column being resolved is from the GROUP BY clause, the procedure searches the SELECT list 'fields' and the columns in the FROM list 'tables'. If 'order' is from the ORDER BY clause, only the SELECT list is being searched. If 'order' is resolved to an Item, then order->item is set to the found Item. If there is no item for the found column (that is, it was resolved into a table field), order->item is 'fixed' and is added to all_fields and ref_pointer_array. ref_pointer_array and all_fields are updated. @param[in] thd Pointer to current thread structure @param[in,out] ref_pointer_array All select, group and order by fields @param[in] tables List of tables to search in (usually FROM clause) @param[in] order Column reference to be resolved @param[in] fields List of fields to search in (usually SELECT list) @param[in,out] all_fields All select, group and order by fields @param[in] is_group_field True if order is a GROUP field, false if ORDER by field @retval FALSE if OK @retval TRUE if error occurred */ static bool find_order_in_list(THD *thd, Ref_ptr_array ref_pointer_array, TABLE_LIST *tables, ORDER *order, List<Item> &fields, List<Item> &all_fields, bool is_group_field) { Item *order_item= *order->item; /* The item from the GROUP/ORDER caluse. */ Item::Type order_item_type; Item **select_item; /* The corresponding item from the SELECT clause. */ Field *from_field; /* The corresponding field from the FROM clause. */ uint counter; enum_resolution_type resolution; /* Local SP variables may be int but are expressions, not positions. (And they can't be used before fix_fields is called for them). */ if (order_item->type() == Item::INT_ITEM && order_item->basic_const_item()) { /* Order by position */ uint count= (uint) order_item->val_int(); if (!count || count > fields.elements) { my_error(ER_BAD_FIELD_ERROR, MYF(0), order_item->full_name(), thd->where); return TRUE; } order->item= &ref_pointer_array[count - 1]; order->in_field_list= 1; return FALSE; } /* Lookup the current GROUP/ORDER field in the SELECT clause. */ select_item= find_item_in_list(order_item, fields, &counter, REPORT_EXCEPT_NOT_FOUND, &resolution); if (!select_item) return TRUE; /* The item is not unique, or some other error occured. */ /* Check whether the resolved field is not ambiguos. */ if (select_item != not_found_item) { Item *view_ref= NULL; /* If we have found field not by its alias in select list but by its original field name, we should additionally check if we have conflict for this name (in case if we would perform lookup in all tables). */ if (resolution == RESOLVED_BEHIND_ALIAS && !order_item->fixed && order_item->fix_fields(thd, order->item)) return TRUE; /* Lookup the current GROUP field in the FROM clause. */ order_item_type= order_item->type(); from_field= (Field*) not_found_field; if ((is_group_field && order_item_type == Item::FIELD_ITEM) || order_item_type == Item::REF_ITEM) { from_field= find_field_in_tables(thd, (Item_ident*) order_item, tables, NULL, &view_ref, IGNORE_ERRORS, TRUE, FALSE); if (!from_field) from_field= (Field*) not_found_field; } if (from_field == not_found_field || (from_field != view_ref_found ? /* it is field of base table => check that fields are same */ ((*select_item)->type() == Item::FIELD_ITEM && ((Item_field*) (*select_item))->field->eq(from_field)) : /* in is field of view table => check that references on translation table are same */ ((*select_item)->type() == Item::REF_ITEM && view_ref->type() == Item::REF_ITEM && ((Item_ref *) (*select_item))->ref == ((Item_ref *) view_ref)->ref))) { /* If there is no such field in the FROM clause, or it is the same field as the one found in the SELECT clause, then use the Item created for the SELECT field. As a result if there was a derived field that 'shadowed' a table field with the same name, the table field will be chosen over the derived field. If we replace *order->item with one from the select list or from a table in the FROM list, we should clean up after removing the old *order->item from the query. The item has not been fixed (so there are no aggregation functions that need cleaning up), but it may contain subqueries that should be unlinked. */ if (*order->item != *select_item) (*order->item)->walk(&Item::clean_up_after_removal, walk_subquery, NULL); order->item= &ref_pointer_array[counter]; order->in_field_list=1; if (resolution == RESOLVED_AGAINST_ALIAS) order->used_alias= true; return FALSE; } else { /* There is a field with the same name in the FROM clause. This is the field that will be chosen. In this case we issue a warning so the user knows that the field from the FROM clause overshadows the column reference from the SELECT list. */ push_warning_printf(thd, Sql_condition::SL_WARNING, ER_NON_UNIQ_ERROR, ER(ER_NON_UNIQ_ERROR), ((Item_ident*) order_item)->field_name, current_thd->where); } } order->in_field_list=0; /* The call to order_item->fix_fields() means that here we resolve 'order_item' to a column from a table in the list 'tables', or to a column in some outer query. Exactly because of the second case we come to this point even if (select_item == not_found_item), inspite of that fix_fields() calls find_item_in_list() one more time. We check order_item->fixed because Item_func_group_concat can put arguments for which fix_fields already was called. group_fix_field= TRUE is to resolve aliases from the SELECT list without creating of Item_ref-s: JOIN::exec() wraps aliased items in SELECT list with Item_copy items. To re-evaluate such a tree that includes Item_copy items we have to refresh Item_copy caches, but: - filesort() never refresh Item_copy items, - end_send_group() checks every record for group boundary by the test_if_group_changed function that obtain data from these Item_copy items, but the copy_fields function that refreshes Item copy items is called after group boundaries only - that is a vicious circle. So we prevent inclusion of Item_copy items. */ bool save_group_fix_field= thd->lex->current_select()->group_fix_field; if (is_group_field) thd->lex->current_select()->group_fix_field= TRUE; bool ret= (!order_item->fixed && (order_item->fix_fields(thd, order->item) || (order_item= *order->item)->check_cols(1))); thd->lex->current_select()->group_fix_field= save_group_fix_field; if (ret) return TRUE; /* Wrong field. */ uint el= all_fields.elements; all_fields.push_front(order_item); /* Add new field to field list. */ ref_pointer_array[el]= order_item; /* If the order_item is a SUM_FUNC_ITEM, when fix_fields is called ref_by is set to order->item which is the address of order_item. But this needs to be address of order_item in the all_fields list. As a result, when it gets replaced with Item_aggregate_ref object in Item::split_sum_func2, we will be able to retrieve the newly created object. */ if (order_item->type() == Item::SUM_FUNC_ITEM) ((Item_sum *)order_item)->ref_by= all_fields.head_ref(); /* Currently, we assume that this assertion holds. If it turns out that it fails for some query, order->item has changed and the old item is removed from the query. In that case, we must call walk() with clean_up_after_removal() on the old order->item. */ DBUG_ASSERT(order_item == *order->item); order->item= &ref_pointer_array[el]; return FALSE; } /** Resolve and setup list of expressions in ORDER BY clause. Change order to point at item in select list. If item isn't a number and doesn't exists in the select list, add it to the the field list. @param thd Thread handler @returns false if success, true if error */ bool setup_order(THD *thd, Ref_ptr_array ref_pointer_array, TABLE_LIST *tables, List<Item> &fields, List<Item> &all_fields, ORDER *order) { DBUG_ASSERT(order); SELECT_LEX *const select= thd->lex->current_select(); thd->where="order clause"; const bool for_union= select->master_unit()->is_union() && select == select->master_unit()->fake_select_lex; const bool is_aggregated= select->is_grouped(); for (uint number= 1; order; order=order->next, number++) { if (find_order_in_list(thd, ref_pointer_array, tables, order, fields, all_fields, false)) return true; if ((*order->item)->with_sum_func) { /* Aggregated expressions in ORDER BY are not supported by SQL standard, but MySQL has some limited support for them. The limitations are checked below: 1. A UNION query is not aggregated, so ordering by a set function is always wrong. */ if (for_union) { my_error(ER_AGGREGATE_ORDER_FOR_UNION, MYF(0), number); return true; } /* 2. A non-aggregated query combined with a set function in ORDER BY that does not contain an outer reference is illegal, because it would cause the query to become aggregated. (Since is_aggregated is false, this expression would cause agg_func_used() to become true). */ if (!is_aggregated && select->agg_func_used()) { my_error(ER_AGGREGATE_ORDER_NON_AGG_QUERY, MYF(0), number); return true; } } } return false; } /** Runs checks mandated by ONLY_FULL_GROUP_BY @param thd THD pointer @returns true if ONLY_FULL_GROUP_BY is violated. */ bool SELECT_LEX::check_only_full_group_by(THD *thd) { bool rc= false; if (is_grouped()) { MEM_ROOT root; /* "root" has very short lifetime, and should not consume much => not instrumented. */ init_sql_alloc(PSI_NOT_INSTRUMENTED, &root, MEM_ROOT_BLOCK_SIZE, 0); { Group_check gc(this, &root); rc= gc.check_query(thd); gc.to_opt_trace(thd); } // scope, to let any destructor run before free_root(). free_root(&root, MYF(0)); } if (!rc && is_distinct() && // aggregate without GROUP => single-row result => don't bother user !(!group_list.elements && agg_func_used())) { Distinct_check dc(this); rc= dc.check_query(thd); } return rc; } /** Do final setup of ORDER BY clause, after the query block is fully resolved. Check that ORDER BY clause is not redundant. Split any aggregate functions. @param thd Thread handler @param hidden_order_field_count Number of fields to delete from ref array if ORDER BY clause is redundant. @returns false if success, true if error */ bool SELECT_LEX::setup_order_final(THD *thd, int hidden_order_field_count) { if (is_implicitly_grouped()) { // Result will contain zero or one row - ordering is redundant empty_order_list(hidden_order_field_count); return false; } if ((master_unit()->is_union() || master_unit()->fake_select_lex) && this != master_unit()->fake_select_lex && !(braces && explicit_limit)) { // Part of UNION which requires global ordering may skip local order empty_order_list(hidden_order_field_count); return false; } for (ORDER *ord= (ORDER *)order_list.first; ord; ord= ord->next) { Item *const item= *ord->item; if (item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM) { item->split_sum_func(thd, ref_ptrs, all_fields); if (thd->is_error()) return true; /* purecov: inspected */ } } return false; } /** Resolve and set up the GROUP BY list. @param thd Thread handler @todo change ER_WRONG_FIELD_WITH_GROUP to more detailed ER_NON_GROUPING_FIELD_USED @returns false if success, true if error */ bool SELECT_LEX::setup_group(THD *thd) { DBUG_ASSERT(group_list.elements); thd->where="group statement"; for (ORDER *group= group_list.first; group; group= group->next) { if (find_order_in_list(thd, ref_ptrs, get_table_list(), group, fields_list, all_fields, true)) return true; if ((*group->item)->with_sum_func) { my_error(ER_WRONG_GROUP_FIELD, MYF(0), (*group->item)->full_name()); return true; } } return false; } /**************************************************************************** ROLLUP handling ****************************************************************************/ /** Replace occurrences of group by fields in an expression by ref items. The function replaces occurrences of group by fields in expr by ref objects for these fields unless they are under aggregate functions. The function also corrects value of the the maybe_null attribute for the items of all subexpressions containing group by fields. @b EXAMPLES @code SELECT a+1 FROM t1 GROUP BY a WITH ROLLUP SELECT SUM(a)+a FROM t1 GROUP BY a WITH ROLLUP @endcode @b IMPLEMENTATION The function recursively traverses the tree of the expr expression, looks for occurrences of the group by fields that are not under aggregate functions and replaces them for the corresponding ref items. @note This substitution is needed GROUP BY queries with ROLLUP if SELECT list contains expressions over group by attributes. @param thd reference to the context @param expr expression to make replacement @param changed[out] returns true if item contains a replaced field item @todo - TODO: Some functions are not null-preserving. For those functions updating of the maybe_null attribute is an overkill. @returns false if success, true if error */ bool SELECT_LEX::change_group_ref(THD *thd, Item_func *expr, bool *changed) { bool arg_changed= false; for (uint i= 0; i < expr->arg_count; i++) { Item **arg= expr->arguments() + i; Item *const item= *arg; if (item->type() == Item::FIELD_ITEM || item->type() == Item::REF_ITEM) { for (ORDER *group= (ORDER *)group_list.first; group; group= group->next) { if (item->eq(*group->item, 0)) { Item *new_item; if (!(new_item= new Item_ref(&context, group->item, 0, item->item_name.ptr()))) return true; /* purecov: inspected */ thd->change_item_tree(arg, new_item); arg_changed= true; } } } else if (item->type() == Item::FUNC_ITEM) { if (change_group_ref(thd, (Item_func *) item, &arg_changed)) return true; } } if (arg_changed) { expr->maybe_null= true; *changed= true; } return false; } /** Resolve items for rollup processing @param thd Thread handler @returns false if success, true if error */ bool SELECT_LEX::resolve_rollup(THD *thd) { List_iterator<Item> it(all_fields); Item *item; while ((item= it++)) { bool found_in_group= false; for (ORDER *group= (ORDER *)group_list.first; group; group= group->next) { if (*group->item == item) { item->maybe_null= true; found_in_group= true; break; } } if (item->type() == Item::FUNC_ITEM && !found_in_group) { bool changed= false; if (change_group_ref(thd, (Item_func *) item, &changed)) return true; /* purecov: inspected */ /* We have to prevent creation of a field in a temporary table for an expression that contains GROUP BY attributes. Marking the expression item as 'with_sum_func' will ensure this. */ if (changed) item->with_sum_func= true; } } return false; } /** @brief validate_gc_assignment Check whether the other values except DEFAULT are assigned for generated columns. @param thd thread handler @param fields Item_fields list to be filled @param values values to fill with @param table table to be checked @return Operation status @retval false OK @retval true Error occured @Note: This function must be called after table->write_set has been filled. */ bool validate_gc_assignment(THD * thd, List<Item> *fields, List<Item> *values, TABLE *table) { Field **fld= NULL; MY_BITMAP *bitmap= table->write_set; bool use_table_field= false; DBUG_ENTER("validate_gc_assignment"); if (!values || (values->elements == 0)) DBUG_RETURN(false); // If fields has no elements, we use all table fields if (fields->elements == 0) { use_table_field= true; fld= table->field; } List_iterator_fast<Item> f(*fields),v(*values); Item *value; while ((value= v++)) { Field *rfield; if (!use_table_field) rfield= ((Item_field *)f++)->field; else rfield= *(fld++); if (rfield->table != table) continue; /* skip non marked fields */ if (!bitmap_is_set(bitmap, rfield->field_index)) continue; if (rfield->gcol_info && value->type() != Item::DEFAULT_VALUE_ITEM) { my_error(ER_NON_DEFAULT_VALUE_FOR_GENERATED_COLUMN, MYF(0), rfield->field_name, rfield->table->s->table_name.str); DBUG_RETURN(true); } } DBUG_RETURN(false); } /** Delete unused columns from merged tables. This function is called recursively for each join nest and/or table in the query block. For each merged table that it finds, each column that contains a subquery and is not marked as used is removed and the translation item is set to NULL. @param tables List of tables and join nests */ void SELECT_LEX::delete_unused_merged_columns(List<TABLE_LIST> *tables) { DBUG_ENTER("delete_unused_merged_columns"); TABLE_LIST *tl; List_iterator<TABLE_LIST> li(*tables); while ((tl= li++)) { if (tl->nested_join == NULL) continue; if (tl->is_merged()) { for (Field_translator *transl= tl->field_translation; transl < tl->field_translation_end; transl++) { DBUG_ASSERT(transl->item->fixed); if (transl->item->has_subquery() && !transl->item->is_derived_used()) { transl->item->walk(&Item::clean_up_after_removal, walk_subquery, (uchar *)this); transl->item= NULL; } } } delete_unused_merged_columns(&tl->nested_join->join_list); } DBUG_VOID_RETURN; } /** @} (end of group Query_Resolver) */
ForcerKing/ShaoqunXu-mysql5.7
sql/sql_resolver.cc
C++
gpl-2.0
121,648
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2009-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.core.soa; import java.util.Collection; import java.util.Map; /** * ServiceRegistry * * @author brozow * @version $Id: $ */ public interface ServiceRegistry { /** * <p>register</p> * * @param serviceProvider a {@link java.lang.Object} object. * @param services a {@link java.lang.Class} object. * @return a {@link org.opennms.core.soa.Registration} object. */ public Registration register(Object serviceProvider, Class<?>... services); /** * <p>register</p> * * @param serviceProvider a {@link java.lang.Object} object. * @param properties a {@link java.util.Map} object. * @param services a {@link java.lang.Class} object. * @return a {@link org.opennms.core.soa.Registration} object. */ public Registration register(Object serviceProvider, Map<String, String> properties, Class<?>... services); /** * <p>findProvider</p> * * @param seviceInterface a {@link java.lang.Class} object. * @param <T> a T object. * @return a T object. */ public <T> T findProvider(Class<T> seviceInterface); /** * <p>findProvider</p> * * @param serviceInterface a {@link java.lang.Class} object. * @param filter a {@link java.lang.String} object. * @param <T> a T object. * @return a T object. */ public <T> T findProvider(Class<T> serviceInterface, String filter); /** * <p>findProviders</p> * * @param service a {@link java.lang.Class} object. * @param <T> a T object. * @return a {@link java.util.Collection} object. */ public <T> Collection<T> findProviders(Class<T> service); /** * <p>findProviders</p> * * @param service a {@link java.lang.Class} object. * @param filter a {@link java.lang.String} object. * @param <T> a T object. * @return a {@link java.util.Collection} object. */ public <T> Collection<T> findProviders(Class<T> service, String filter); /** * <p>addListener</p> * * @param service a {@link java.lang.Class} object. * @param listener a {@link org.opennms.core.soa.RegistrationListener} object. * @param <T> a T object. */ public <T> void addListener(Class<T> service, RegistrationListener<T> listener); /** * <p>addListener</p> * * @param service a {@link java.lang.Class} object. * @param listener a {@link org.opennms.core.soa.RegistrationListener} object. * @param notifyForExistingProviders a boolean. * @param <T> a T object. */ public <T> void addListener(Class<T> service, RegistrationListener<T> listener, boolean notifyForExistingProviders); /** * <p>removeListener</p> * * @param service a {@link java.lang.Class} object. * @param listener a {@link org.opennms.core.soa.RegistrationListener} object. * @param <T> a T object. */ public <T> void removeListener(Class<T> service, RegistrationListener<T> listener); }
vishwaAbhinav/OpenNMS
core/soa/src/main/java/org/opennms/core/soa/ServiceRegistry.java
Java
gpl-2.0
4,248
<div id="<?php echo $iname; ?>messages" class="messages"> <?php // if there are messages loop through all messages if ($this->getInput('messages')) { foreach ($this->getInput('messages') as $message) { ?> <div class="messageblock"> <div class="header"> <div class="datetime"><?php echo $message["date_time"]; ?></div> <div class="username"> <span class="name"><?php echo $message["name"]; ?></span> <span class="said">said...</span> </div> </div> <div class="messagetext"><?php echo $message["message"]; ?></div> </div> <?php } } // end loop ?> </div>
peeto/DarkChat
src/web/displaymessages.php
PHP
gpl-2.0
667
""" SALTS XBMC Addon Copyright (C) 2014 tknorris This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import re import urllib import urlparse import kodi import dom_parser from salts_lib import scraper_utils from salts_lib.constants import FORCE_NO_MATCH from salts_lib.constants import QUALITIES from salts_lib.constants import VIDEO_TYPES import scraper BASE_URL = 'http://watch8now.me' class Scraper(scraper.Scraper): base_url = BASE_URL def __init__(self, timeout=scraper.DEFAULT_TIMEOUT): self.timeout = timeout self.base_url = kodi.get_setting('%s-base_url' % (self.get_name())) @classmethod def provides(cls): return frozenset([VIDEO_TYPES.TVSHOW, VIDEO_TYPES.EPISODE]) @classmethod def get_name(cls): return 'Watch8Now' def resolve_link(self, link): html = self._http_get(link, cache_limit=.5) match = re.search('<iframe[^>]*src="([^"]+)', html, re.I) if match: return match.group(1) else: match = re.search('Nothing in HERE<br>([^<]+)', html, re.I) if match: return match.group(1).strip() return link def get_sources(self, video): source_url = self.get_url(video) hosters = [] if source_url and source_url != FORCE_NO_MATCH: url = urlparse.urljoin(self.base_url, source_url) html = self._http_get(url, cache_limit=.5) for table_cell in dom_parser.parse_dom(html, 'td', {'class': 'domain'}): match = re.search('href="([^"]+)(?:[^>]+>){2}\s*([^<]+)', table_cell) if match: link, host = match.groups() hoster = {'multi-part': False, 'host': host, 'class': self, 'quality': scraper_utils.get_quality(video, host, QUALITIES.HIGH), 'views': None, 'rating': None, 'url': link, 'direct': False} hosters.append(hoster) return hosters def _get_episode_url(self, show_url, video): episode_pattern = 'href="([^"]+[sS]%s[eE]%s\.html)"' % (video.season, video.episode) title_pattern = 'href="(?P<url>[^"]+[sS]\d+[eE]\d+\.html)"(?:[^>]+>){6}(?P<title>[^<]+)' return self._default_get_episode_url(show_url, video, episode_pattern, title_pattern) def search(self, video_type, title, year, season=''): search_url = urlparse.urljoin(self.base_url, '/search?q=') search_url += urllib.quote_plus(title) html = self._http_get(search_url, cache_limit=8) results = [] for item in dom_parser.parse_dom(html, 'h4', {'class': 'media-heading'}): match = re.search('href="([^"]+)">([^<]+)', item) if match: url, match_title = match.groups() result = {'url': scraper_utils.pathify_url(url), 'title': scraper_utils.cleanse_title(match_title), 'year': ''} results.append(result) return results
felipenaselva/repo.felipe
plugin.video.salts/scrapers/watch8now_scraper.py
Python
gpl-2.0
3,576
/* * Open-source multi-Physics Phenomena Analyzer (OP2A) ver. 0.1 * * Copyright (c) 2015 MINKWAN KIM * * Initial Developed Date: May 26, 2015 * Author: Minkwan Kim * * OP2A_ProblemCommon.hpp * - * */ #ifndef OP2A_PROBLEMCOMMON_HPP_ #define OP2A_PROBLEMCOMMON_HPP_ #include <string> #include <vector> using namespace std; namespace OP2A{ namespace Setup{ /* * Class for Basic Problem setup * * @author Minkwan Kim * @version 1.0 25/05/2015 */ class ProblemBasic { public: string title; string module; }; } } #endif /* OP2A_PROBLEMCOMMON_HPP_ */
minkwankim/OP2A
OP2A/Setup/include/OP2A_ProblemCommon.hpp
C++
gpl-2.0
593
<?php /* * This file is part of SeAT * * Copyright (C) 2015 to 2020 Leon Jacobs * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; /** * Class CreateCorporationInfosTestTable. */ class CreateCorporationInfosTestTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('corporation_infos', function (Blueprint $table) { $table->bigInteger('corporation_id')->primary(); $table->string('name'); $table->string('ticker'); $table->integer('member_count'); $table->bigInteger('ceo_id'); $table->bigInteger('alliance_id')->nullable(); $table->text('description')->nullable(); $table->double('tax_rate'); $table->dateTime('date_founded')->nullable(); $table->bigInteger('creator_id'); $table->string('url')->nullable(); $table->integer('faction_id')->nullable(); $table->integer('home_station_id')->nullable(); $table->bigInteger('shares')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('corporation_infos'); } }
eveseat/web
tests/database/migrations/2020_05_08_085856_create_corporation_infos_test_table.php
PHP
gpl-2.0
2,126
/* * Copyright (C) 2005 - 2011 MaNGOS <http://www.getmangos.org/> * * Copyright (C) 2008 - 2011 TrinityCore <http://www.trinitycore.org/> * * Copyright (C) 2011 - 2012 TrilliumEMU <http://trilliumx.code-engine.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "InstanceScript.h" #include "DatabaseEnv.h" #include "Map.h" #include "Player.h" #include "GameObject.h" #include "Creature.h" #include "CreatureAI.h" #include "Log.h" #include "LFGMgr.h" void InstanceScript::SaveToDB() { std::string data = GetSaveData(); if (data.empty()) return; PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_INSTANCE_DATA); stmt->setUInt32(0, GetCompletedEncounterMask()); stmt->setString(1, data); stmt->setUInt32(2, instance->GetInstanceId()); CharacterDatabase.Execute(stmt); } void InstanceScript::HandleGameObject(uint64 GUID, bool open, GameObject *go) { if (!go) go = instance->GetGameObject(GUID); if (go) go->SetGoState(open ? GO_STATE_ACTIVE : GO_STATE_READY); else sLog->outDebug(LOG_FILTER_TSCR, "TSCR: InstanceScript: HandleGameObject failed"); } bool InstanceScript::IsEncounterInProgress() const { for (std::vector<BossInfo>::const_iterator itr = bosses.begin(); itr != bosses.end(); ++itr) if (itr->state == IN_PROGRESS) return true; return false; } void InstanceScript::LoadMinionData(const MinionData *data) { while (data->entry) { if (data->bossId < bosses.size()) minions.insert(std::make_pair(data->entry, MinionInfo(&bosses[data->bossId]))); ++data; } sLog->outDebug(LOG_FILTER_TSCR, "InstanceScript::LoadMinionData: " UI64FMTD " minions loaded.", uint64(minions.size())); } void InstanceScript::LoadDoorData(const DoorData *data) { while (data->entry) { if (data->bossId < bosses.size()) doors.insert(std::make_pair(data->entry, DoorInfo(&bosses[data->bossId], data->type, BoundaryType(data->boundary)))); ++data; } sLog->outDebug(LOG_FILTER_TSCR, "InstanceScript::LoadDoorData: " UI64FMTD " doors loaded.", uint64(doors.size())); } void InstanceScript::UpdateMinionState(Creature *minion, EncounterState state) { switch (state) { case NOT_STARTED: if (!minion->isAlive()) minion->Respawn(); else if (minion->isInCombat()) minion->AI()->EnterEvadeMode(); break; case IN_PROGRESS: if (!minion->isAlive()) minion->Respawn(); else if (!minion->getVictim()) minion->AI()->DoZoneInCombat(); break; default: break; } } void InstanceScript::UpdateDoorState(GameObject *door) { DoorInfoMap::iterator lower = doors.lower_bound(door->GetEntry()); DoorInfoMap::iterator upper = doors.upper_bound(door->GetEntry()); if (lower == upper) return; bool open = true; for (DoorInfoMap::iterator itr = lower; itr != upper && open; ++itr) { switch (itr->second.type) { case DOOR_TYPE_ROOM: open = (itr->second.bossInfo->state != IN_PROGRESS); break; case DOOR_TYPE_PASSAGE: open = (itr->second.bossInfo->state == DONE); break; case DOOR_TYPE_SPAWN_HOLE: open = (itr->second.bossInfo->state == IN_PROGRESS); break; default: break; } } door->SetGoState(open ? GO_STATE_ACTIVE : GO_STATE_READY); } void InstanceScript::AddDoor(GameObject *door, bool add) { DoorInfoMap::iterator lower = doors.lower_bound(door->GetEntry()); DoorInfoMap::iterator upper = doors.upper_bound(door->GetEntry()); if (lower == upper) return; for (DoorInfoMap::iterator itr = lower; itr != upper; ++itr) { if (add) { itr->second.bossInfo->door[itr->second.type].insert(door); switch (itr->second.boundary) { default: case BOUNDARY_NONE: break; case BOUNDARY_N: case BOUNDARY_S: itr->second.bossInfo->boundary[itr->second.boundary] = door->GetPositionX(); break; case BOUNDARY_E: case BOUNDARY_W: itr->second.bossInfo->boundary[itr->second.boundary] = door->GetPositionY(); break; case BOUNDARY_NW: case BOUNDARY_SE: itr->second.bossInfo->boundary[itr->second.boundary] = door->GetPositionX() + door->GetPositionY(); break; case BOUNDARY_NE: case BOUNDARY_SW: itr->second.bossInfo->boundary[itr->second.boundary] = door->GetPositionX() - door->GetPositionY(); break; } } else itr->second.bossInfo->door[itr->second.type].erase(door); } if (add) UpdateDoorState(door); } void InstanceScript::AddMinion(Creature *minion, bool add) { MinionInfoMap::iterator itr = minions.find(minion->GetEntry()); if (itr == minions.end()) return; if (add) itr->second.bossInfo->minion.insert(minion); else itr->second.bossInfo->minion.erase(minion); } bool InstanceScript::SetBossState(uint32 id, EncounterState state) { if (id < bosses.size()) { BossInfo *bossInfo = &bosses[id]; if (bossInfo->state == TO_BE_DECIDED) // loading { bossInfo->state = state; //sLog->outError("Inialize boss %u state as %u.", id, (uint32)state); return false; } else { if (bossInfo->state == state) return false; if (state == DONE) for (MinionSet::iterator i = bossInfo->minion.begin(); i != bossInfo->minion.end(); ++i) if ((*i)->isWorldBoss() && (*i)->isAlive()) return false; bossInfo->state = state; SaveToDB(); } for (uint32 type = 0; type < MAX_DOOR_TYPES; ++type) for (DoorSet::iterator i = bossInfo->door[type].begin(); i != bossInfo->door[type].end(); ++i) UpdateDoorState(*i); for (MinionSet::iterator i = bossInfo->minion.begin(); i != bossInfo->minion.end(); ++i) UpdateMinionState(*i, state); return true; } return false; } std::string InstanceScript::LoadBossState(const char * data) { if (!data) return NULL; std::istringstream loadStream(data); uint32 buff; uint32 bossId = 0; for (std::vector<BossInfo>::iterator i = bosses.begin(); i != bosses.end(); ++i, ++bossId) { loadStream >> buff; if (buff < TO_BE_DECIDED) SetBossState(bossId, (EncounterState)buff); } return loadStream.str(); } std::string InstanceScript::GetBossSaveData() { std::ostringstream saveStream; for (std::vector<BossInfo>::iterator i = bosses.begin(); i != bosses.end(); ++i) saveStream << (uint32)i->state << ' '; return saveStream.str(); } void InstanceScript::DoUseDoorOrButton(uint64 uiGuid, uint32 uiWithRestoreTime, bool bUseAlternativeState) { if (!uiGuid) return; GameObject* pGo = instance->GetGameObject(uiGuid); if (pGo) { if (pGo->GetGoType() == GAMEOBJECT_TYPE_DOOR || pGo->GetGoType() == GAMEOBJECT_TYPE_BUTTON) { if (pGo->getLootState() == GO_READY) pGo->UseDoorOrButton(uiWithRestoreTime, bUseAlternativeState); else if (pGo->getLootState() == GO_ACTIVATED) pGo->ResetDoorOrButton(); } else sLog->outError("SD2: Script call DoUseDoorOrButton, but gameobject entry %u is type %u.", pGo->GetEntry(), pGo->GetGoType()); } } void InstanceScript::DoRespawnGameObject(uint64 uiGuid, uint32 uiTimeToDespawn) { if (GameObject* pGo = instance->GetGameObject(uiGuid)) { //not expect any of these should ever be handled if (pGo->GetGoType() == GAMEOBJECT_TYPE_FISHINGNODE || pGo->GetGoType() == GAMEOBJECT_TYPE_DOOR || pGo->GetGoType() == GAMEOBJECT_TYPE_BUTTON || pGo->GetGoType() == GAMEOBJECT_TYPE_TRAP) return; if (pGo->isSpawned()) return; pGo->SetRespawnTime(uiTimeToDespawn); } } void InstanceScript::DoUpdateWorldState(uint32 uiStateId, uint32 uiStateData) { Map::PlayerList const& lPlayers = instance->GetPlayers(); if (!lPlayers.isEmpty()) { for (Map::PlayerList::const_iterator itr = lPlayers.begin(); itr != lPlayers.end(); ++itr) if (Player *pPlayer = itr->getSource()) pPlayer->SendUpdateWorldState(uiStateId, uiStateData); } else sLog->outDebug(LOG_FILTER_TSCR, "TSCR: DoUpdateWorldState attempt send data but no players in map."); } // Send Notify to all players in instance void InstanceScript::DoSendNotifyToInstance(const char *format, ...) { InstanceMap::PlayerList const &PlayerList = instance->GetPlayers(); InstanceMap::PlayerList::const_iterator i; if (!PlayerList.isEmpty()) { va_list ap; va_start(ap, format); for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) { if (Player *pPlayer = i->getSource()) if (WorldSession *pSession = pPlayer->GetSession()) pSession->SendNotification(format, ap); } va_end(ap); } } // Update Achievement Criteria for all players in instance void InstanceScript::DoUpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 /*= 0*/, uint32 miscValue2 /*= 0*/, Unit* unit /*= NULL*/) { Map::PlayerList const &PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) if (Player *pPlayer = i->getSource()) pPlayer->UpdateAchievementCriteria(type, miscValue1, miscValue2, unit); } // Start timed achievement for all players in instance void InstanceScript::DoStartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry) { Map::PlayerList const &PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) if (Player *pPlayer = i->getSource()) pPlayer->GetAchievementMgr().StartTimedAchievement(type, entry); } // Stop timed achievement for all players in instance void InstanceScript::DoStopTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry) { Map::PlayerList const &PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) if (Player *pPlayer = i->getSource()) pPlayer->GetAchievementMgr().RemoveTimedAchievement(type, entry); } // Remove Auras due to Spell on all players in instance void InstanceScript::DoRemoveAurasDueToSpellOnPlayers(uint32 spell) { Map::PlayerList const& PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) { for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr) { if (Player* player = itr->getSource()) { player->RemoveAurasDueToSpell(spell); if (Pet* pet = player->GetPet()) pet->RemoveAurasDueToSpell(spell); } } } } // Cast spell on all players in instance void InstanceScript::DoCastSpellOnPlayers(uint32 spell) { Map::PlayerList const &PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) if (Player* player = i->getSource()) player->CastSpell(player, spell, true); } bool InstanceScript::CheckAchievementCriteriaMeet(uint32 criteria_id, Player const* /*source*/, Unit const* /*target*/ /*= NULL*/, uint32 /*miscvalue1*/ /*= 0*/) { sLog->outError("Achievement system call InstanceScript::CheckAchievementCriteriaMeet but instance script for map %u not have implementation for achievement criteria %u", instance->GetId(), criteria_id); return false; } void InstanceScript::SendEncounterUnit(uint32 type, Unit* unit /*= NULL*/, uint8 param1 /*= 0*/, uint8 param2 /*= 0*/) { // size of this packet is at most 15 (usually less) WorldPacket data(SMSG_UPDATE_INSTANCE_ENCOUNTER_UNIT, 15); data << uint32(type); switch (type) { case ENCOUNTER_FRAME_ADD: case ENCOUNTER_FRAME_REMOVE: case 2: data.append(unit->GetPackGUID()); data << uint8(param1); break; case 3: case 4: case 6: data << uint8(param1); data << uint8(param2); break; case 5: data << uint8(param1); break; case 7: default: break; } instance->SendToPlayers(&data); } void InstanceScript::UpdateEncounterState(EncounterCreditType type, uint32 creditEntry, Unit* source) { DungeonEncounterList const* encounters = sObjectMgr->GetDungeonEncounterList(instance->GetId(), instance->GetDifficulty()); if (!encounters) return; for (DungeonEncounterList::const_iterator itr = encounters->begin(); itr != encounters->end(); ++itr) { if ((*itr)->creditType == type && (*itr)->creditEntry == creditEntry) { completedEncounters |= 1 << (*itr)->dbcEntry->encounterIndex; sLog->outDebug(LOG_FILTER_TSCR, "Instance %s (instanceId %u) completed encounter %s", instance->GetMapName(), instance->GetInstanceId(), (*itr)->dbcEntry->encounterName[0]); if (uint32 dungeonId = (*itr)->lastEncounterDungeon) { Map::PlayerList const& players = instance->GetPlayers(); if (!players.isEmpty()) for (Map::PlayerList::const_iterator i = players.begin(); i != players.end(); ++i) if (Player* player = i->getSource()) if (!source || player->IsAtGroupRewardDistance(source)) sLFGMgr->RewardDungeonDonefor (dungeonId, player); } return; } } }
Kr4v3n5/Core
src/server/game/Instances/InstanceScript.cpp
C++
gpl-2.0
15,351
<?php /** * @file * Customize the display of a complete webform. * * This file may be renamed "webform-form-[nid].tpl.php" to target a specific * webform on your site. Or you can leave it "webform-form.tpl.php" to affect * all webforms on your site. * * Available variables: * - $form: The complete form array. * - $nid: The node ID of the Webform. * * The $form array contains two main pieces: * - $form['submitted']: The main content of the user-created form. * - $form['details']: Internal information stored by Webform. */ ?> <div class="row"> <div class="col-md-4 col-sm-12"></div> <div class="col-md-4 col-sm-12"> <div id="content-contact-form"> <div id="form-contacto"> <h3>Contáctanos</h3> <?php // Print out the main part of the form. // Feel free to break this up and move the pieces within the array. print drupal_render($form['submitted']); // Always print out the entire $form. This renders the remaining pieces of the // form that haven't yet been rendered above. print drupal_render_children($form); ?> </div> </div> </div> <div class="col-md-4 col-sm-12"></div> </div>
eforerop2888/fotografias
sites/all/themes/fotografias/templates/webform-form-33.tpl.php
PHP
gpl-2.0
1,215
import mainUi.main mainUi.main.main()
MiiRaGe/cryptanalysis-tools
run.py
Python
gpl-2.0
39
/* * Copyright (C) 2014-2017 StormCore * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "PlayerAI.h" #include "SpellAuras.h" #include "SpellAuraEffects.h" enum Spells { /* Generic */ SPELL_AUTO_SHOT = 75, SPELL_SHOOT = 3018, SPELL_THROW = 2764, SPELL_SHOOT_WAND = 5019, /* Warrior - Generic */ SPELL_BATTLE_STANCE = 2457, SPELL_BERSERKER_STANCE = 2458, SPELL_DEFENSIVE_STANCE = 71, SPELL_CHARGE = 11578, SPELL_INTERCEPT = 20252, SPELL_ENRAGED_REGEN = 55694, SPELL_INTIMIDATING_SHOUT= 5246, SPELL_PUMMEL = 6552, SPELL_SHIELD_BASH = 72, SPELL_BLOODRAGE = 2687, /* Warrior - Arms */ SPELL_SWEEPING_STRIKES = 12328, SPELL_MORTAL_STRIKE = 12294, SPELL_BLADESTORM = 46924, SPELL_REND = 47465, SPELL_RETALIATION = 20230, SPELL_SHATTERING_THROW = 64382, SPELL_THUNDER_CLAP = 47502, /* Warrior - Fury */ SPELL_DEATH_WISH = 12292, SPELL_BLOODTHIRST = 23881, PASSIVE_TITANS_GRIP = 46917, SPELL_DEMO_SHOUT = 47437, SPELL_EXECUTE = 47471, SPELL_HEROIC_FURY = 60970, SPELL_RECKLESSNESS = 1719, SPELL_PIERCING_HOWL = 12323, /* Warrior - Protection */ SPELL_VIGILANCE = 50720, SPELL_DEVASTATE = 20243, SPELL_SHOCKWAVE = 46968, SPELL_CONCUSSION_BLOW = 12809, SPELL_DISARM = 676, SPELL_LAST_STAND = 12975, SPELL_SHIELD_BLOCK = 2565, SPELL_SHIELD_SLAM = 47488, SPELL_SHIELD_WALL = 871, SPELL_SPELL_REFLECTION = 23920, /* Paladin - Generic */ SPELL_PAL_AURA_MASTERY = 31821, SPELL_LAY_ON_HANDS = 48788, SPELL_BLESSING_OF_MIGHT = 48932, SPELL_AVENGING_WRATH = 31884, SPELL_DIVINE_PROTECTION = 498, SPELL_DIVINE_SHIELD = 642, SPELL_HAMMER_OF_JUSTICE = 10308, SPELL_HAND_OF_FREEDOM = 1044, SPELL_HAND_OF_PROTECTION = 10278, SPELL_HAND_OF_SACRIFICE = 6940, /* Paladin - Holy*/ PASSIVE_ILLUMINATION = 20215, SPELL_HOLY_SHOCK = 20473, SPELL_BEACON_OF_LIGHT = 53563, SPELL_CONSECRATION = 48819, SPELL_FLASH_OF_LIGHT = 48785, SPELL_HOLY_LIGHT = 48782, SPELL_DIVINE_FAVOR = 20216, SPELL_DIVINE_ILLUMINATION = 31842, /* Paladin - Protection */ SPELL_BLESS_OF_SANC = 20911, SPELL_HOLY_SHIELD = 20925, SPELL_AVENGERS_SHIELD = 48827, SPELL_DIVINE_SACRIFICE = 64205, SPELL_HAMMER_OF_RIGHTEOUS = 53595, SPELL_RIGHTEOUS_FURY = 25780, SPELL_SHIELD_OF_RIGHTEOUS = 61411, /* Paladin - Retribution */ SPELL_SEAL_OF_COMMAND = 20375, SPELL_CRUSADER_STRIKE = 35395, SPELL_DIVINE_STORM = 53385, SPELL_JUDGEMENT = 20271, SPELL_HAMMER_OF_WRATH = 48806, /* Hunter - Generic */ SPELL_DETERRENCE = 19263, SPELL_EXPLOSIVE_TRAP = 49067, SPELL_FREEZING_ARROW = 60192, SPELL_RAPID_FIRE = 3045, SPELL_KILL_SHOT = 61006, SPELL_MULTI_SHOT = 49048, SPELL_VIPER_STING = 3034, /* Hunter - Beast Mastery */ SPELL_BESTIAL_WRATH = 19574, PASSIVE_BEAST_WITHIN = 34692, PASSIVE_BEAST_MASTERY = 53270, /* Hunter - Marksmanship */ SPELL_AIMED_SHOT = 19434, PASSIVE_TRUESHOT_AURA = 19506, SPELL_CHIMERA_SHOT = 53209, SPELL_ARCANE_SHOT = 49045, SPELL_STEADY_SHOT = 49052, SPELL_READINESS = 23989, SPELL_SILENCING_SHOT = 34490, /* Hunter - Survival */ PASSIVE_LOCK_AND_LOAD = 56344, SPELL_WYVERN_STING = 19386, SPELL_EXPLOSIVE_SHOT = 53301, SPELL_BLACK_ARROW = 3674, /* Rogue - Generic */ SPELL_DISMANTLE = 51722, SPELL_EVASION = 26669, SPELL_KICK = 1766, SPELL_VANISH = 26889, SPELL_BLIND = 2094, SPELL_CLOAK_OF_SHADOWS = 31224, /* Rogue - Assassination */ SPELL_COLD_BLOOD = 14177, SPELL_MUTILATE = 1329, SPELL_HUNGER_FOR_BLOOD = 51662, SPELL_ENVENOM = 57993, /* Rogue - Combat */ SPELL_SINISTER_STRIKE = 48637, SPELL_BLADE_FLURRY = 13877, SPELL_ADRENALINE_RUSH = 13750, SPELL_KILLING_SPREE = 51690, SPELL_EVISCERATE = 48668, /* Rogue - Sublety */ SPELL_HEMORRHAGE = 16511, SPELL_PREMEDITATION = 14183, SPELL_SHADOW_DANCE = 51713, SPELL_PREPARATION = 14185, SPELL_SHADOWSTEP = 36554, /* Priest - Generic */ SPELL_FEAR_WARD = 6346, SPELL_POWER_WORD_FORT = 48161, SPELL_DIVINE_SPIRIT = 48073, SPELL_SHADOW_PROTECTION = 48169, SPELL_DIVINE_HYMN = 64843, SPELL_HYMN_OF_HOPE = 64901, SPELL_SHADOW_WORD_DEATH = 48158, SPELL_PSYCHIC_SCREAM = 10890, /* Priest - Discipline */ PASSIVE_SOUL_WARDING = 63574, SPELL_POWER_INFUSION = 10060, SPELL_PENANCE = 47540, SPELL_PAIN_SUPPRESSION = 33206, SPELL_INNER_FOCUS = 14751, SPELL_POWER_WORD_SHIELD = 48066, /* Priest - Holy */ PASSIVE_SPIRIT_REDEMPTION = 20711, SPELL_DESPERATE_PRAYER = 19236, SPELL_GUARDIAN_SPIRIT = 47788, SPELL_FLASH_HEAL = 48071, SPELL_RENEW = 48068, /* Priest - Shadow */ SPELL_VAMPIRIC_EMBRACE = 15286, SPELL_SHADOWFORM = 15473, SPELL_VAMPIRIC_TOUCH = 34914, SPELL_MIND_FLAY = 15407, SPELL_MIND_BLAST = 48127, SPELL_SHADOW_WORD_PAIN = 48125, SPELL_DEVOURING_PLAGUE = 48300, SPELL_DISPERSION = 47585, /* Death Knight - Generic */ SPELL_DEATH_GRIP = 49576, SPELL_STRANGULATE = 47476, SPELL_EMPOWER_RUNE_WEAP = 47568, SPELL_ICEBORN_FORTITUDE = 48792, SPELL_ANTI_MAGIC_SHELL = 48707, SPELL_DEATH_COIL_DK = 49895, SPELL_MIND_FREEZE = 47528, SPELL_ICY_TOUCH = 49909, AURA_FROST_FEVER = 55095, SPELL_PLAGUE_STRIKE = 49921, AURA_BLOOD_PLAGUE = 55078, SPELL_PESTILENCE = 50842, /* Death Knight - Blood */ SPELL_RUNE_TAP = 48982, SPELL_HYSTERIA = 49016, SPELL_HEART_STRIKE = 55050, SPELL_DEATH_STRIKE = 49924, SPELL_BLOOD_STRIKE = 49930, SPELL_MARK_OF_BLOOD = 49005, SPELL_VAMPIRIC_BLOOD = 55233, /* Death Knight - Frost */ PASSIVE_ICY_TALONS = 50887, SPELL_FROST_STRIKE = 49143, SPELL_HOWLING_BLAST = 49184, SPELL_UNBREAKABLE_ARMOR = 51271, SPELL_OBLITERATE = 51425, SPELL_DEATHCHILL = 49796, /* Death Knight - Unholy */ PASSIVE_UNHOLY_BLIGHT = 49194, PASSIVE_MASTER_OF_GHOUL = 52143, SPELL_SCOURGE_STRIKE = 55090, SPELL_DEATH_AND_DECAY = 49938, SPELL_ANTI_MAGIC_ZONE = 51052, SPELL_SUMMON_GARGOYLE = 49206, /* Shaman - Generic */ SPELL_HEROISM = 32182, SPELL_BLOODLUST = 2825, SPELL_GROUNDING_TOTEM = 8177, /* Shaman - Elemental*/ PASSIVE_ELEMENTAL_FOCUS = 16164, SPELL_TOTEM_OF_WRATH = 30706, SPELL_THUNDERSTORM = 51490, SPELL_LIGHTNING_BOLT = 49238, SPELL_EARTH_SHOCK = 49231, SPELL_FLAME_SHOCK = 49233, SPELL_LAVA_BURST = 60043, SPELL_CHAIN_LIGHTNING = 49271, SPELL_ELEMENTAL_MASTERY = 16166, /* Shaman - Enhancement */ PASSIVE_SPIRIT_WEAPONS = 16268, SPELL_LAVA_LASH = 60103, SPELL_FERAL_SPIRIT = 51533, AURA_MAELSTROM_WEAPON = 53817, SPELL_STORMSTRIKE = 17364, SPELL_SHAMANISTIC_RAGE = 30823, /* Shaman - Restoration*/ SPELL_SHA_NATURE_SWIFT = 591, SPELL_MANA_TIDE_TOTEM = 590, SPELL_EARTH_SHIELD = 49284, SPELL_RIPTIDE = 61295, SPELL_HEALING_WAVE = 49273, SPELL_LESSER_HEAL_WAVE = 49276, SPELL_TIDAL_FORCE = 55198, /* Mage - Generic */ SPELL_DAMPEN_MAGIC = 43015, SPELL_EVOCATION = 12051, SPELL_MANA_SHIELD = 43020, SPELL_MIRROR_IMAGE = 55342, SPELL_SPELLSTEAL = 30449, SPELL_COUNTERSPELL = 2139, SPELL_ICE_BLOCK = 45438, /* Mage - Arcane */ SPELL_FOCUS_MAGIC = 54646, SPELL_ARCANE_POWER = 12042, SPELL_ARCANE_BARRAGE = 44425, SPELL_ARCANE_BLAST = 42897, AURA_ARCANE_BLAST = 36032, SPELL_ARCANE_MISSILES = 42846, SPELL_PRESENCE_OF_MIND = 12043, /* Mage - Fire */ SPELL_PYROBLAST = 11366, SPELL_COMBUSTION = 11129, SPELL_LIVING_BOMB = 44457, SPELL_FIREBALL = 42833, SPELL_FIRE_BLAST = 42873, SPELL_DRAGONS_BREATH = 31661, SPELL_BLAST_WAVE = 11113, /* Mage - Frost */ SPELL_ICY_VEINS = 12472, SPELL_ICE_BARRIER = 11426, SPELL_DEEP_FREEZE = 44572, SPELL_FROST_NOVA = 42917, SPELL_FROSTBOLT = 42842, SPELL_COLD_SNAP = 11958, SPELL_ICE_LANCE = 42914, /* Warlock - Generic */ SPELL_FEAR = 6215, SPELL_HOWL_OF_TERROR = 17928, SPELL_CORRUPTION = 47813, SPELL_DEATH_COIL_W = 47860, SPELL_SHADOW_BOLT = 47809, SPELL_INCINERATE = 47838, SPELL_IMMOLATE = 47811, SPELL_SEED_OF_CORRUPTION = 47836, /* Warlock - Affliction */ PASSIVE_SIPHON_LIFE = 63108, SPELL_UNSTABLE_AFFLICTION = 30108, SPELL_HAUNT = 48181, SPELL_CURSE_OF_AGONY = 47864, SPELL_DRAIN_SOUL = 47855, /* Warlock - Demonology */ SPELL_SOUL_LINK = 19028, SPELL_DEMONIC_EMPOWERMENT = 47193, SPELL_METAMORPHOSIS = 59672, SPELL_IMMOLATION_AURA = 50589, SPELL_DEMON_CHARGE = 54785, AURA_DECIMATION = 63167, AURA_MOLTEN_CORE = 71165, SPELL_SOUL_FIRE = 47825, /* Warlock - Destruction */ SPELL_SHADOWBURN = 17877, SPELL_CONFLAGRATE = 17962, SPELL_CHAOS_BOLT = 50796, SPELL_SHADOWFURY = 47847, /* Druid - Generic */ SPELL_BARKSKIN = 22812, SPELL_INNERVATE = 29166, /* Druid - Balance */ SPELL_INSECT_SWARM = 5570, SPELL_MOONKIN_FORM = 24858, SPELL_STARFALL = 48505, SPELL_TYPHOON = 61384, AURA_ECLIPSE_LUNAR = 48518, SPELL_MOONFIRE = 48463, SPELL_STARFIRE = 48465, SPELL_WRATH = 48461, /* Druid - Feral */ SPELL_CAT_FORM = 768, SPELL_SURVIVAL_INSTINCTS = 61336, SPELL_MANGLE = 33917, SPELL_BERSERK = 50334, SPELL_MANGLE_CAT = 48566, SPELL_FERAL_CHARGE_CAT = 49376, SPELL_RAKE = 48574, SPELL_RIP = 49800, SPELL_SAVAGE_ROAR = 52610, SPELL_TIGER_FURY = 50213, SPELL_CLAW = 48570, SPELL_DASH = 33357, SPELL_MAIM = 49802, /* Druid - Restoration */ SPELL_SWIFTMEND = 18562, SPELL_TREE_OF_LIFE = 33891, SPELL_WILD_GROWTH = 48438, SPELL_NATURE_SWIFTNESS = 17116, SPELL_TRANQUILITY = 48447, SPELL_NOURISH = 50464, SPELL_HEALING_TOUCH = 48378, SPELL_REJUVENATION = 48441, SPELL_REGROWTH = 48443, SPELL_LIFEBLOOM = 48451 }; bool PlayerAI::IsPlayerHealer(Player const* who) { if (!who) return false; switch (who->getClass()) { case CLASS_WARRIOR: case CLASS_HUNTER: case CLASS_ROGUE: case CLASS_DEATH_KNIGHT: case CLASS_MAGE: case CLASS_WARLOCK: case CLASS_DEMON_HUNTER: default: return false; case CLASS_PALADIN: return who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_PALADIN_HOLY; case CLASS_PRIEST: return who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_PRIEST_DISCIPLINE || who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_PRIEST_HOLY; case CLASS_SHAMAN: return who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_SHAMAN_RESTORATION; case CLASS_MONK: return who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_MONK_MISTWEAVER; case CLASS_DRUID: return who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_DRUID_RESTORATION; } } bool PlayerAI::IsPlayerRangedAttacker(Player const* who) { if (!who) return false; switch (who->getClass()) { case CLASS_WARRIOR: case CLASS_PALADIN: case CLASS_ROGUE: case CLASS_DEATH_KNIGHT: default: return false; case CLASS_MAGE: case CLASS_WARLOCK: return true; case CLASS_HUNTER: { // check if we have a ranged weapon equipped Item const* rangedSlot = who->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED); if (ItemTemplate const* rangedTemplate = rangedSlot ? rangedSlot->GetTemplate() : nullptr) if ((1 << rangedTemplate->GetSubClass()) & ITEM_SUBCLASS_MASK_WEAPON_RANGED) return true; return false; } case CLASS_PRIEST: return who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_PRIEST_SHADOW; case CLASS_SHAMAN: return who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_SHAMAN_ELEMENTAL; case CLASS_DRUID: return who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_DRUID_BALANCE; } } PlayerAI::TargetedSpell PlayerAI::VerifySpellCast(uint32 spellId, Unit* target) { // Find highest spell rank that we know uint32 knownRank, nextRank; if (me->HasSpell(spellId)) { // this will save us some lookups if the player has the highest rank (expected case) knownRank = spellId; nextRank = sSpellMgr->GetNextSpellInChain(spellId); } else { knownRank = 0; nextRank = sSpellMgr->GetFirstSpellInChain(spellId); } while (nextRank && me->HasSpell(nextRank)) { knownRank = nextRank; nextRank = sSpellMgr->GetNextSpellInChain(knownRank); } if (!knownRank) return {}; SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(knownRank); if (!spellInfo) return {}; if (me->GetSpellHistory()->HasGlobalCooldown(spellInfo)) return {}; Spell* spell = new Spell(me, spellInfo, TRIGGERED_NONE); if (spell->CanAutoCast(target)) return{ spell, target }; delete spell; return {}; } PlayerAI::TargetedSpell PlayerAI::VerifySpellCast(uint32 spellId, SpellTarget target) { Unit* pTarget = nullptr; switch (target) { case TARGET_NONE: break; case TARGET_VICTIM: pTarget = me->GetVictim(); if (!pTarget) return {}; break; case TARGET_CHARMER: pTarget = me->GetCharmer(); if (!pTarget) return {}; break; case TARGET_SELF: pTarget = me; break; } return VerifySpellCast(spellId, pTarget); } PlayerAI::TargetedSpell PlayerAI::SelectSpellCast(PossibleSpellVector& spells) { if (spells.empty()) return{}; uint32 totalWeights = 0; for (PossibleSpell const& wSpell : spells) totalWeights += wSpell.second; TargetedSpell selected; uint32 randNum = urand(0, totalWeights - 1); for (PossibleSpell const& wSpell : spells) { if (selected) { delete wSpell.first.first; continue; } if (randNum < wSpell.second) selected = wSpell.first; else { randNum -= wSpell.second; delete wSpell.first.first; } } spells.clear(); return selected; } void PlayerAI::DoRangedAttackIfReady() { if (me->HasUnitState(UNIT_STATE_CASTING)) return; if (!me->isAttackReady(RANGED_ATTACK)) return; Unit* victim = me->GetVictim(); if (!victim) return; uint32 rangedAttackSpell = 0; Item const* rangedItem = me->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED); if (ItemTemplate const* rangedTemplate = rangedItem ? rangedItem->GetTemplate() : nullptr) { switch (rangedTemplate->GetSubClass()) { case ITEM_SUBCLASS_WEAPON_BOW: case ITEM_SUBCLASS_WEAPON_GUN: case ITEM_SUBCLASS_WEAPON_CROSSBOW: rangedAttackSpell = SPELL_SHOOT; break; case ITEM_SUBCLASS_WEAPON_THROWN: rangedAttackSpell = SPELL_THROW; break; case ITEM_SUBCLASS_WEAPON_WAND: rangedAttackSpell = SPELL_SHOOT_WAND; break; } } if (!rangedAttackSpell) return; me->CastSpell(victim, rangedAttackSpell, TRIGGERED_CAST_DIRECTLY); me->resetAttackTimer(RANGED_ATTACK); } void PlayerAI::DoAutoAttackIfReady() { if (IsRangedAttacker()) DoRangedAttackIfReady(); else DoMeleeAttackIfReady(); } void PlayerAI::CancelAllShapeshifts() { std::list<AuraEffect*> const& shapeshiftAuras = me->GetAuraEffectsByType(SPELL_AURA_MOD_SHAPESHIFT); std::set<Aura*> removableShapeshifts; for (AuraEffect* auraEff : shapeshiftAuras) { Aura* aura = auraEff->GetBase(); if (!aura) continue; SpellInfo const* auraInfo = aura->GetSpellInfo(); if (!auraInfo) continue; if (auraInfo->HasAttribute(SPELL_ATTR0_CANT_CANCEL)) continue; if (!auraInfo->IsPositive() || auraInfo->IsPassive()) continue; removableShapeshifts.insert(aura); } for (Aura* aura : removableShapeshifts) me->RemoveOwnedAura(aura, AURA_REMOVE_BY_CANCEL); } struct UncontrolledTargetSelectPredicate : public std::unary_function<Unit*, bool> { bool operator()(Unit const* target) const { return !target->HasBreakableByDamageCrowdControlAura(); } }; Unit* SimpleCharmedPlayerAI::SelectAttackTarget() const { if (Unit* charmer = me->GetCharmer()) return charmer->IsAIEnabled ? charmer->GetAI()->SelectTarget(SELECT_TARGET_RANDOM, 0, UncontrolledTargetSelectPredicate()) : charmer->GetVictim(); return nullptr; } PlayerAI::TargetedSpell SimpleCharmedPlayerAI::SelectAppropriateCastForSpec() { PossibleSpellVector spells; /* switch (me->getClass()) { case CLASS_WARRIOR: if (!me->IsWithinMeleeRange(me->GetVictim())) { VerifyAndPushSpellCast(spells, SPELL_CHARGE, TARGET_VICTIM, 15); VerifyAndPushSpellCast(spells, SPELL_INTERCEPT, TARGET_VICTIM, 10); } VerifyAndPushSpellCast(spells, SPELL_ENRAGED_REGEN, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_INTIMIDATING_SHOUT, TARGET_VICTIM, 4); if (me->GetVictim() && me->GetVictim()->HasUnitState(UNIT_STATE_CASTING)) { VerifyAndPushSpellCast(spells, SPELL_PUMMEL, TARGET_VICTIM, 15); VerifyAndPushSpellCast(spells, SPELL_SHIELD_BASH, TARGET_VICTIM, 15); } VerifyAndPushSpellCast(spells, SPELL_BLOODRAGE, TARGET_NONE, 5); switch (GetSpec()) { case TALENT_SPEC_WARRIOR_PROTECTION: VerifyAndPushSpellCast(spells, SPELL_SHOCKWAVE, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_CONCUSSION_BLOW, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_DISARM, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_LAST_STAND, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_SHIELD_BLOCK, TARGET_NONE, 1); VerifyAndPushSpellCast(spells, SPELL_SHIELD_SLAM, TARGET_VICTIM, 4); VerifyAndPushSpellCast(spells, SPELL_SHIELD_WALL, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_SPELL_REFLECTION, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_DEVASTATE, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_REND, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_THUNDER_CLAP, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_DEMO_SHOUT, TARGET_VICTIM, 1); break; case TALENT_SPEC_WARRIOR_ARMS: VerifyAndPushSpellCast(spells, SPELL_SWEEPING_STRIKES, TARGET_NONE, 2); VerifyAndPushSpellCast(spells, SPELL_MORTAL_STRIKE, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_BLADESTORM, TARGET_NONE, 10); VerifyAndPushSpellCast(spells, SPELL_REND, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_RETALIATION, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_SHATTERING_THROW, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_SWEEPING_STRIKES, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_THUNDER_CLAP, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_EXECUTE, TARGET_VICTIM, 15); break; case TALENT_SPEC_WARRIOR_FURY: VerifyAndPushSpellCast(spells, SPELL_DEATH_WISH, TARGET_NONE, 10); VerifyAndPushSpellCast(spells, SPELL_BLOODTHIRST, TARGET_VICTIM, 4); VerifyAndPushSpellCast(spells, SPELL_DEMO_SHOUT, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_EXECUTE, TARGET_VICTIM, 15); VerifyAndPushSpellCast(spells, SPELL_HEROIC_FURY, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_RECKLESSNESS, TARGET_NONE, 8); VerifyAndPushSpellCast(spells, SPELL_PIERCING_HOWL, TARGET_VICTIM, 2); break; } break; case CLASS_PALADIN: VerifyAndPushSpellCast(spells, SPELL_AURA_MASTERY, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_LAY_ON_HANDS, TARGET_CHARMER, 8); VerifyAndPushSpellCast(spells, SPELL_BLESSING_OF_MIGHT, TARGET_CHARMER, 8); VerifyAndPushSpellCast(spells, SPELL_AVENGING_WRATH, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_DIVINE_PROTECTION, TARGET_NONE, 4); VerifyAndPushSpellCast(spells, SPELL_DIVINE_SHIELD, TARGET_NONE, 2); VerifyAndPushSpellCast(spells, SPELL_HAMMER_OF_JUSTICE, TARGET_VICTIM, 6); VerifyAndPushSpellCast(spells, SPELL_HAND_OF_FREEDOM, TARGET_SELF, 3); VerifyAndPushSpellCast(spells, SPELL_HAND_OF_PROTECTION, TARGET_SELF, 1); if (Creature* creatureCharmer = ObjectAccessor::GetCreature(*me, me->GetCharmerGUID())) { if (creatureCharmer->IsDungeonBoss() || creatureCharmer->isWorldBoss()) VerifyAndPushSpellCast(spells, SPELL_HAND_OF_SACRIFICE, creatureCharmer, 10); else VerifyAndPushSpellCast(spells, SPELL_HAND_OF_PROTECTION, creatureCharmer, 3); } switch (GetSpec()) { case TALENT_SPEC_PALADIN_PROTECTION: VerifyAndPushSpellCast(spells, SPELL_HAMMER_OF_RIGHTEOUS, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_DIVINE_SACRIFICE, TARGET_NONE, 2); VerifyAndPushSpellCast(spells, SPELL_SHIELD_OF_RIGHTEOUS, TARGET_VICTIM, 4); VerifyAndPushSpellCast(spells, SPELL_JUDGEMENT, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_CONSECRATION, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_HOLY_SHIELD, TARGET_NONE, 1); break; case TALENT_SPEC_PALADIN_HOLY: VerifyAndPushSpellCast(spells, SPELL_HOLY_SHOCK, TARGET_CHARMER, 3); VerifyAndPushSpellCast(spells, SPELL_HOLY_SHOCK, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_FLASH_OF_LIGHT, TARGET_CHARMER, 4); VerifyAndPushSpellCast(spells, SPELL_HOLY_LIGHT, TARGET_CHARMER, 3); VerifyAndPushSpellCast(spells, SPELL_DIVINE_FAVOR, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_DIVINE_ILLUMINATION, TARGET_NONE, 3); break; case TALENT_SPEC_PALADIN_RETRIBUTION: VerifyAndPushSpellCast(spells, SPELL_CRUSADER_STRIKE, TARGET_VICTIM, 4); VerifyAndPushSpellCast(spells, SPELL_DIVINE_STORM, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_JUDGEMENT, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_HAMMER_OF_WRATH, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_RIGHTEOUS_FURY, TARGET_NONE, 2); break; } break; case CLASS_HUNTER: VerifyAndPushSpellCast(spells, SPELL_DETERRENCE, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_EXPLOSIVE_TRAP, TARGET_NONE, 1); VerifyAndPushSpellCast(spells, SPELL_FREEZING_ARROW, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_RAPID_FIRE, TARGET_NONE, 10); VerifyAndPushSpellCast(spells, SPELL_KILL_SHOT, TARGET_VICTIM, 10); if (me->GetVictim() && me->GetVictim()->getPowerType() == POWER_MANA && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_VIPER_STING, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_VIPER_STING, TARGET_VICTIM, 5); switch (GetSpec()) { case TALENT_SPEC_HUNTER_BEASTMASTER: VerifyAndPushSpellCast(spells, SPELL_AIMED_SHOT, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_ARCANE_SHOT, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_STEADY_SHOT, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_MULTI_SHOT, TARGET_VICTIM, 2); break; case TALENT_SPEC_HUNTER_MARKSMAN: VerifyAndPushSpellCast(spells, SPELL_AIMED_SHOT, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_CHIMERA_SHOT, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_ARCANE_SHOT, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_STEADY_SHOT, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_READINESS, TARGET_NONE, 10); VerifyAndPushSpellCast(spells, SPELL_SILENCING_SHOT, TARGET_VICTIM, 5); break; case TALENT_SPEC_HUNTER_SURVIVAL: VerifyAndPushSpellCast(spells, SPELL_EXPLOSIVE_SHOT, TARGET_VICTIM, 8); VerifyAndPushSpellCast(spells, SPELL_BLACK_ARROW, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_MULTI_SHOT, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_STEADY_SHOT, TARGET_VICTIM, 1); break; } break; case CLASS_ROGUE: { VerifyAndPushSpellCast(spells, SPELL_DISMANTLE, TARGET_VICTIM, 8); VerifyAndPushSpellCast(spells, SPELL_EVASION, TARGET_NONE, 8); VerifyAndPushSpellCast(spells, SPELL_VANISH, TARGET_NONE, 4); VerifyAndPushSpellCast(spells, SPELL_BLIND, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_CLOAK_OF_SHADOWS, TARGET_NONE, 2); uint32 builder = 0, finisher = 0; switch (GetSpec()) { case TALENT_SPEC_ROGUE_ASSASSINATION: builder = SPELL_MUTILATE, finisher = SPELL_ENVENOM; VerifyAndPushSpellCast(spells, SPELL_COLD_BLOOD, TARGET_NONE, 20); break; case TALENT_SPEC_ROGUE_COMBAT: builder = SPELL_SINISTER_STRIKE, finisher = SPELL_EVISCERATE; VerifyAndPushSpellCast(spells, SPELL_ADRENALINE_RUSH, TARGET_NONE, 6); VerifyAndPushSpellCast(spells, SPELL_BLADE_FLURRY, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_KILLING_SPREE, TARGET_NONE, 25); break; case TALENT_SPEC_ROGUE_SUBTLETY: builder = SPELL_HEMORRHAGE, finisher = SPELL_EVISCERATE; VerifyAndPushSpellCast(spells, SPELL_PREPARATION, TARGET_NONE, 10); if (!me->IsWithinMeleeRange(me->GetVictim())) VerifyAndPushSpellCast(spells, SPELL_SHADOWSTEP, TARGET_VICTIM, 25); VerifyAndPushSpellCast(spells, SPELL_SHADOW_DANCE, TARGET_NONE, 10); break; } if (Unit* victim = me->GetVictim()) { if (victim->HasUnitState(UNIT_STATE_CASTING)) VerifyAndPushSpellCast(spells, SPELL_KICK, TARGET_VICTIM, 25); uint8 const cp = me->GetPower(POWER_COMBO_POINTS); if (cp >= 4) VerifyAndPushSpellCast(spells, finisher, TARGET_VICTIM, 10); if (cp <= 4) VerifyAndPushSpellCast(spells, builder, TARGET_VICTIM, 5); } break; } case CLASS_PRIEST: VerifyAndPushSpellCast(spells, SPELL_FEAR_WARD, TARGET_SELF, 2); VerifyAndPushSpellCast(spells, SPELL_POWER_WORD_FORT, TARGET_CHARMER, 1); VerifyAndPushSpellCast(spells, SPELL_DIVINE_SPIRIT, TARGET_CHARMER, 1); VerifyAndPushSpellCast(spells, SPELL_SHADOW_PROTECTION, TARGET_CHARMER, 2); VerifyAndPushSpellCast(spells, SPELL_DIVINE_HYMN, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_HYMN_OF_HOPE, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_SHADOW_WORD_DEATH, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_PSYCHIC_SCREAM, TARGET_VICTIM, 3); switch (GetSpec()) { case TALENT_SPEC_PRIEST_DISCIPLINE: VerifyAndPushSpellCast(spells, SPELL_POWER_WORD_SHIELD, TARGET_CHARMER, 3); VerifyAndPushSpellCast(spells, SPELL_INNER_FOCUS, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_PAIN_SUPPRESSION, TARGET_CHARMER, 15); VerifyAndPushSpellCast(spells, SPELL_POWER_INFUSION, TARGET_CHARMER, 10); VerifyAndPushSpellCast(spells, SPELL_PENANCE, TARGET_CHARMER, 3); VerifyAndPushSpellCast(spells, SPELL_FLASH_HEAL, TARGET_CHARMER, 1); break; case TALENT_SPEC_PRIEST_HOLY: VerifyAndPushSpellCast(spells, SPELL_DESPERATE_PRAYER, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_GUARDIAN_SPIRIT, TARGET_CHARMER, 5); VerifyAndPushSpellCast(spells, SPELL_FLASH_HEAL, TARGET_CHARMER, 1); VerifyAndPushSpellCast(spells, SPELL_RENEW, TARGET_CHARMER, 3); break; case TALENT_SPEC_PRIEST_SHADOW: if (!me->HasAura(SPELL_SHADOWFORM)) { VerifyAndPushSpellCast(spells, SPELL_SHADOWFORM, TARGET_NONE, 100); break; } if (Unit* victim = me->GetVictim()) { if (!victim->GetAuraApplicationOfRankedSpell(SPELL_VAMPIRIC_TOUCH, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_VAMPIRIC_TOUCH, TARGET_VICTIM, 4); if (!victim->GetAuraApplicationOfRankedSpell(SPELL_SHADOW_WORD_PAIN, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_SHADOW_WORD_PAIN, TARGET_VICTIM, 3); if (!victim->GetAuraApplicationOfRankedSpell(SPELL_DEVOURING_PLAGUE, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_DEVOURING_PLAGUE, TARGET_VICTIM, 4); } VerifyAndPushSpellCast(spells, SPELL_MIND_BLAST, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_MIND_FLAY, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_DISPERSION, TARGET_NONE, 10); break; } break; case CLASS_DEATH_KNIGHT: { if (!me->IsWithinMeleeRange(me->GetVictim())) VerifyAndPushSpellCast(spells, SPELL_DEATH_GRIP, TARGET_VICTIM, 25); VerifyAndPushSpellCast(spells, SPELL_STRANGULATE, TARGET_VICTIM, 15); VerifyAndPushSpellCast(spells, SPELL_EMPOWER_RUNE_WEAP, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_ICEBORN_FORTITUDE, TARGET_NONE, 15); VerifyAndPushSpellCast(spells, SPELL_ANTI_MAGIC_SHELL, TARGET_NONE, 10); bool hasFF = false, hasBP = false; if (Unit* victim = me->GetVictim()) { if (victim->HasUnitState(UNIT_STATE_CASTING)) VerifyAndPushSpellCast(spells, SPELL_MIND_FREEZE, TARGET_VICTIM, 25); hasFF = !!victim->GetAuraApplicationOfRankedSpell(AURA_FROST_FEVER, me->GetGUID()), hasBP = !!victim->GetAuraApplicationOfRankedSpell(AURA_BLOOD_PLAGUE, me->GetGUID()); if (hasFF && hasBP) VerifyAndPushSpellCast(spells, SPELL_PESTILENCE, TARGET_VICTIM, 3); if (!hasFF) VerifyAndPushSpellCast(spells, SPELL_ICY_TOUCH, TARGET_VICTIM, 4); if (!hasBP) VerifyAndPushSpellCast(spells, SPELL_PLAGUE_STRIKE, TARGET_VICTIM, 4); } switch (GetSpec()) { case TALENT_SPEC_DEATHKNIGHT_BLOOD: VerifyAndPushSpellCast(spells, SPELL_RUNE_TAP, TARGET_NONE, 2); VerifyAndPushSpellCast(spells, SPELL_HYSTERIA, TARGET_SELF, 5); if (Creature* creatureCharmer = ObjectAccessor::GetCreature(*me, me->GetCharmerGUID())) if (!creatureCharmer->IsDungeonBoss() && !creatureCharmer->isWorldBoss()) VerifyAndPushSpellCast(spells, SPELL_HYSTERIA, creatureCharmer, 15); VerifyAndPushSpellCast(spells, SPELL_HEART_STRIKE, TARGET_VICTIM, 2); if (hasFF && hasBP) VerifyAndPushSpellCast(spells, SPELL_DEATH_STRIKE, TARGET_VICTIM, 8); VerifyAndPushSpellCast(spells, SPELL_DEATH_COIL_DK, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_MARK_OF_BLOOD, TARGET_VICTIM, 20); VerifyAndPushSpellCast(spells, SPELL_VAMPIRIC_BLOOD, TARGET_NONE, 10); break; case TALENT_SPEC_DEATHKNIGHT_FROST: if (hasFF && hasBP) VerifyAndPushSpellCast(spells, SPELL_OBLITERATE, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_HOWLING_BLAST, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_UNBREAKABLE_ARMOR, TARGET_NONE, 10); VerifyAndPushSpellCast(spells, SPELL_DEATHCHILL, TARGET_NONE, 10); VerifyAndPushSpellCast(spells, SPELL_FROST_STRIKE, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_BLOOD_STRIKE, TARGET_VICTIM, 1); break; case TALENT_SPEC_DEATHKNIGHT_UNHOLY: if (hasFF && hasBP) VerifyAndPushSpellCast(spells, SPELL_SCOURGE_STRIKE, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_DEATH_AND_DECAY, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_ANTI_MAGIC_ZONE, TARGET_NONE, 8); VerifyAndPushSpellCast(spells, SPELL_SUMMON_GARGOYLE, TARGET_VICTIM, 7); VerifyAndPushSpellCast(spells, SPELL_BLOOD_STRIKE, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_DEATH_COIL_DK, TARGET_VICTIM, 3); break; } break; } case CLASS_SHAMAN: VerifyAndPushSpellCast(spells, SPELL_HEROISM, TARGET_NONE, 25); VerifyAndPushSpellCast(spells, SPELL_BLOODLUST, TARGET_NONE, 25); VerifyAndPushSpellCast(spells, SPELL_GROUNDING_TOTEM, TARGET_NONE, 2); switch (GetSpec()) { case TALENT_SPEC_SHAMAN_RESTORATION: if (Unit* charmer = me->GetCharmer()) if (!charmer->GetAuraApplicationOfRankedSpell(SPELL_EARTH_SHIELD, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_EARTH_SHIELD, charmer, 2); if (me->HasAura(SPELL_SHA_NATURE_SWIFT)) VerifyAndPushSpellCast(spells, SPELL_HEALING_WAVE, TARGET_CHARMER, 20); else VerifyAndPushSpellCast(spells, SPELL_LESSER_HEAL_WAVE, TARGET_CHARMER, 1); VerifyAndPushSpellCast(spells, SPELL_TIDAL_FORCE, TARGET_NONE, 4); VerifyAndPushSpellCast(spells, SPELL_SHA_NATURE_SWIFT, TARGET_NONE, 4); VerifyAndPushSpellCast(spells, SPELL_MANA_TIDE_TOTEM, TARGET_NONE, 3); break; case TALENT_SPEC_SHAMAN_ELEMENTAL: if (Unit* victim = me->GetVictim()) { if (victim->GetAuraOfRankedSpell(SPELL_FLAME_SHOCK, GetGUID())) VerifyAndPushSpellCast(spells, SPELL_LAVA_BURST, TARGET_VICTIM, 5); else VerifyAndPushSpellCast(spells, SPELL_FLAME_SHOCK, TARGET_VICTIM, 3); } VerifyAndPushSpellCast(spells, SPELL_CHAIN_LIGHTNING, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_LIGHTNING_BOLT, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_ELEMENTAL_MASTERY, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_THUNDERSTORM, TARGET_NONE, 3); break; case TALENT_SPEC_SHAMAN_ENHANCEMENT: if (Aura const* maelstrom = me->GetAura(AURA_MAELSTROM_WEAPON)) if (maelstrom->GetStackAmount() == 5) VerifyAndPushSpellCast(spells, SPELL_LIGHTNING_BOLT, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_STORMSTRIKE, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_EARTH_SHOCK, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_LAVA_LASH, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_SHAMANISTIC_RAGE, TARGET_NONE, 10); break; } break; case CLASS_MAGE: if (me->GetVictim() && me->GetVictim()->HasUnitState(UNIT_STATE_CASTING)) VerifyAndPushSpellCast(spells, SPELL_COUNTERSPELL, TARGET_VICTIM, 25); VerifyAndPushSpellCast(spells, SPELL_DAMPEN_MAGIC, TARGET_CHARMER, 2); VerifyAndPushSpellCast(spells, SPELL_EVOCATION, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_MANA_SHIELD, TARGET_NONE, 1); VerifyAndPushSpellCast(spells, SPELL_MIRROR_IMAGE, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_SPELLSTEAL, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_ICE_BLOCK, TARGET_NONE, 1); VerifyAndPushSpellCast(spells, SPELL_ICY_VEINS, TARGET_NONE, 3); switch (GetSpec()) { case TALENT_SPEC_MAGE_ARCANE: if (Aura* abAura = me->GetAura(AURA_ARCANE_BLAST)) if (abAura->GetStackAmount() >= 3) VerifyAndPushSpellCast(spells, SPELL_ARCANE_MISSILES, TARGET_VICTIM, 7); VerifyAndPushSpellCast(spells, SPELL_ARCANE_BLAST, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_ARCANE_BARRAGE, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_ARCANE_POWER, TARGET_NONE, 8); VerifyAndPushSpellCast(spells, SPELL_PRESENCE_OF_MIND, TARGET_NONE, 7); break; case TALENT_SPEC_MAGE_FIRE: if (me->GetVictim() && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_LIVING_BOMB)) VerifyAndPushSpellCast(spells, SPELL_LIVING_BOMB, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_COMBUSTION, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_FIREBALL, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_FIRE_BLAST, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_DRAGONS_BREATH, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_BLAST_WAVE, TARGET_VICTIM, 1); break; case TALENT_SPEC_MAGE_FROST: VerifyAndPushSpellCast(spells, SPELL_DEEP_FREEZE, TARGET_VICTIM, 10); VerifyAndPushSpellCast(spells, SPELL_FROST_NOVA, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_FROSTBOLT, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_COLD_SNAP, TARGET_VICTIM, 5); if (me->GetVictim() && me->GetVictim()->HasAuraState(AURA_STATE_FROZEN, nullptr, me)) VerifyAndPushSpellCast(spells, SPELL_ICE_LANCE, TARGET_VICTIM, 5); break; } break; case CLASS_WARLOCK: VerifyAndPushSpellCast(spells, SPELL_DEATH_COIL_W, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_FEAR, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_SEED_OF_CORRUPTION, TARGET_VICTIM, 4); VerifyAndPushSpellCast(spells, SPELL_HOWL_OF_TERROR, TARGET_NONE, 2); if (me->GetVictim() && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_CORRUPTION, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_CORRUPTION, TARGET_VICTIM, 10); switch (GetSpec()) { case TALENT_SPEC_WARLOCK_AFFLICTION: if (Unit* victim = me->GetVictim()) { VerifyAndPushSpellCast(spells, SPELL_SHADOW_BOLT, TARGET_VICTIM, 7); if (!victim->GetAuraApplicationOfRankedSpell(SPELL_UNSTABLE_AFFLICTION, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_UNSTABLE_AFFLICTION, TARGET_VICTIM, 8); if (!victim->GetAuraApplicationOfRankedSpell(SPELL_HAUNT, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_HAUNT, TARGET_VICTIM, 8); if (!victim->GetAuraApplicationOfRankedSpell(SPELL_CURSE_OF_AGONY, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_CURSE_OF_AGONY, TARGET_VICTIM, 4); if (victim->HealthBelowPct(25)) VerifyAndPushSpellCast(spells, SPELL_DRAIN_SOUL, TARGET_VICTIM, 100); } break; case TALENT_SPEC_WARLOCK_DEMONOLOGY: VerifyAndPushSpellCast(spells, SPELL_METAMORPHOSIS, TARGET_NONE, 15); VerifyAndPushSpellCast(spells, SPELL_SHADOW_BOLT, TARGET_VICTIM, 7); if (me->HasAura(AURA_DECIMATION)) VerifyAndPushSpellCast(spells, SPELL_SOUL_FIRE, TARGET_VICTIM, 100); if (me->HasAura(SPELL_METAMORPHOSIS)) { VerifyAndPushSpellCast(spells, SPELL_IMMOLATION_AURA, TARGET_NONE, 30); if (!me->IsWithinMeleeRange(me->GetVictim())) VerifyAndPushSpellCast(spells, SPELL_DEMON_CHARGE, TARGET_VICTIM, 20); } if (me->GetVictim() && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_IMMOLATE, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_IMMOLATE, TARGET_VICTIM, 5); if (me->HasAura(AURA_MOLTEN_CORE)) VerifyAndPushSpellCast(spells, SPELL_INCINERATE, TARGET_VICTIM, 10); break; case TALENT_SPEC_WARLOCK_DESTRUCTION: if (me->GetVictim() && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_IMMOLATE, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_IMMOLATE, TARGET_VICTIM, 8); if (me->GetVictim() && me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_IMMOLATE, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_CONFLAGRATE, TARGET_VICTIM, 8); VerifyAndPushSpellCast(spells, SPELL_SHADOWFURY, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_CHAOS_BOLT, TARGET_VICTIM, 10); VerifyAndPushSpellCast(spells, SPELL_SHADOWBURN, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_INCINERATE, TARGET_VICTIM, 7); break; } break; case CLASS_MONK: switch (GetSpec()) { case TALENT_SPEC_MONK_BREWMASTER: case TALENT_SPEC_MONK_BATTLEDANCER: case TALENT_SPEC_MONK_MISTWEAVER: break; } break; case CLASS_DRUID: VerifyAndPushSpellCast(spells, SPELL_INNERVATE, TARGET_CHARMER, 5); VerifyAndPushSpellCast(spells, SPELL_BARKSKIN, TARGET_NONE, 5); switch (GetSpec()) { case TALENT_SPEC_DRUID_RESTORATION: if (!me->HasAura(SPELL_TREE_OF_LIFE)) { CancelAllShapeshifts(); VerifyAndPushSpellCast(spells, SPELL_TREE_OF_LIFE, TARGET_NONE, 100); break; } VerifyAndPushSpellCast(spells, SPELL_TRANQUILITY, TARGET_NONE, 10); VerifyAndPushSpellCast(spells, SPELL_NATURE_SWIFTNESS, TARGET_NONE, 7); if (Creature* creatureCharmer = ObjectAccessor::GetCreature(*me, me->GetCharmerGUID())) { VerifyAndPushSpellCast(spells, SPELL_NOURISH, creatureCharmer, 5); VerifyAndPushSpellCast(spells, SPELL_WILD_GROWTH, creatureCharmer, 5); if (!creatureCharmer->GetAuraApplicationOfRankedSpell(SPELL_REJUVENATION, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_REJUVENATION, creatureCharmer, 8); if (!creatureCharmer->GetAuraApplicationOfRankedSpell(SPELL_REGROWTH, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_REGROWTH, creatureCharmer, 8); uint8 lifebloomStacks = 0; if (Aura const* lifebloom = creatureCharmer->GetAura(SPELL_LIFEBLOOM, me->GetGUID())) lifebloomStacks = lifebloom->GetStackAmount(); if (lifebloomStacks < 3) VerifyAndPushSpellCast(spells, SPELL_LIFEBLOOM, creatureCharmer, 5); if (creatureCharmer->GetAuraApplicationOfRankedSpell(SPELL_REJUVENATION) || creatureCharmer->GetAuraApplicationOfRankedSpell(SPELL_REGROWTH)) VerifyAndPushSpellCast(spells, SPELL_SWIFTMEND, creatureCharmer, 10); if (me->HasAura(SPELL_NATURE_SWIFTNESS)) VerifyAndPushSpellCast(spells, SPELL_HEALING_TOUCH, creatureCharmer, 100); } break; case TALENT_SPEC_DRUID_BALANCE: { if (!me->HasAura(SPELL_MOONKIN_FORM)) { CancelAllShapeshifts(); VerifyAndPushSpellCast(spells, SPELL_MOONKIN_FORM, TARGET_NONE, 100); break; } uint32 const mainAttackSpell = me->HasAura(AURA_ECLIPSE_LUNAR) ? SPELL_STARFIRE : SPELL_WRATH; VerifyAndPushSpellCast(spells, SPELL_STARFALL, TARGET_NONE, 20); VerifyAndPushSpellCast(spells, mainAttackSpell, TARGET_VICTIM, 10); if (me->GetVictim() && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_INSECT_SWARM, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_INSECT_SWARM, TARGET_VICTIM, 7); if (me->GetVictim() && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_MOONFIRE, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_MOONFIRE, TARGET_VICTIM, 5); if (me->GetVictim() && me->GetVictim()->HasUnitState(UNIT_STATE_CASTING)) VerifyAndPushSpellCast(spells, SPELL_TYPHOON, TARGET_NONE, 15); break; } case TALENT_SPEC_DRUID_CAT: case TALENT_SPEC_DRUID_BEAR: if (!me->HasAura(SPELL_CAT_FORM)) { CancelAllShapeshifts(); VerifyAndPushSpellCast(spells, SPELL_CAT_FORM, TARGET_NONE, 100); break; } VerifyAndPushSpellCast(spells, SPELL_BERSERK, TARGET_NONE, 20); VerifyAndPushSpellCast(spells, SPELL_SURVIVAL_INSTINCTS, TARGET_NONE, 15); VerifyAndPushSpellCast(spells, SPELL_TIGER_FURY, TARGET_NONE, 15); VerifyAndPushSpellCast(spells, SPELL_DASH, TARGET_NONE, 5); if (Unit* victim = me->GetVictim()) { uint8 const cp = me->GetPower(POWER_COMBO_POINTS); if (victim->HasUnitState(UNIT_STATE_CASTING) && cp >= 1) VerifyAndPushSpellCast(spells, SPELL_MAIM, TARGET_VICTIM, 25); if (!me->IsWithinMeleeRange(victim)) VerifyAndPushSpellCast(spells, SPELL_FERAL_CHARGE_CAT, TARGET_VICTIM, 25); if (cp >= 4) VerifyAndPushSpellCast(spells, SPELL_RIP, TARGET_VICTIM, 50); if (cp <= 4) { VerifyAndPushSpellCast(spells, SPELL_MANGLE_CAT, TARGET_VICTIM, 10); VerifyAndPushSpellCast(spells, SPELL_CLAW, TARGET_VICTIM, 5); if (!victim->GetAuraApplicationOfRankedSpell(SPELL_RAKE, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_RAKE, TARGET_VICTIM, 8); if (!me->HasAura(SPELL_SAVAGE_ROAR)) VerifyAndPushSpellCast(spells, SPELL_SAVAGE_ROAR, TARGET_NONE, 15); } } break; } break; case CLASS_DEMON_HUNTER: switch (GetSpec()) { case TALENT_SPEC_DEMON_HUNTER_HAVOC: case TALENT_SPEC_DEMON_HUNTER_VENGEANCE: break; } break; } */ return SelectSpellCast(spells); } static const float CASTER_CHASE_DISTANCE = 28.0f; void SimpleCharmedPlayerAI::UpdateAI(const uint32 diff) { Creature* charmer = me->GetCharmer() ? me->GetCharmer()->ToCreature() : nullptr; if (!charmer) return; //kill self if charm aura has infinite duration if (charmer->IsInEvadeMode()) { Player::AuraEffectList const& auras = me->GetAuraEffectsByType(SPELL_AURA_MOD_CHARM); for (Player::AuraEffectList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter) if ((*iter)->GetCasterGUID() == charmer->GetGUID() && (*iter)->GetBase()->IsPermanent()) { me->KillSelf(); return; } } if (charmer->IsInCombat()) { Unit* target = me->GetVictim(); if (!target || !charmer->IsValidAttackTarget(target) || target->HasBreakableByDamageCrowdControlAura()) { target = SelectAttackTarget(); if (!target) return; if (IsRangedAttacker()) { _chaseCloser = !me->IsWithinLOSInMap(target); if (_chaseCloser) AttackStart(target); else AttackStartCaster(target, CASTER_CHASE_DISTANCE); } else AttackStart(target); _forceFacing = true; } if (me->IsStopped() && !me->HasUnitState(UNIT_STATE_CANNOT_TURN)) { float targetAngle = me->GetAngle(target); if (_forceFacing || fabs(me->GetOrientation() - targetAngle) > 0.4f) { me->SetFacingTo(targetAngle); _forceFacing = false; } } if (_castCheckTimer <= diff) { if (me->HasUnitState(UNIT_STATE_CASTING)) _castCheckTimer = 0; else { if (IsRangedAttacker()) { // chase to zero if the target isn't in line of sight bool inLOS = me->IsWithinLOSInMap(target); if (_chaseCloser != !inLOS) { _chaseCloser = !inLOS; if (_chaseCloser) AttackStart(target); else AttackStartCaster(target, CASTER_CHASE_DISTANCE); } } if (TargetedSpell shouldCast = SelectAppropriateCastForSpec()) DoCastAtTarget(shouldCast); _castCheckTimer = 500; } } else _castCheckTimer -= diff; DoAutoAttackIfReady(); } else { me->AttackStop(); me->CastStop(); me->StopMoving(); me->GetMotionMaster()->Clear(); me->GetMotionMaster()->MoveFollow(charmer, PET_FOLLOW_DIST, PET_FOLLOW_ANGLE); } } void SimpleCharmedPlayerAI::OnCharmed(bool apply) { if (apply) { me->CastStop(); me->AttackStop(); me->StopMoving(); me->GetMotionMaster()->Clear(); me->GetMotionMaster()->MovePoint(0, me->GetPosition(), false); // force re-sync of current position for all clients } else { me->CastStop(); me->AttackStop(); // @todo only voluntary movement (don't cancel stuff like death grip or charge mid-animation) me->GetMotionMaster()->Clear(); me->StopMoving(); } }
Ragebones/StormCore
src/server/game/AI/PlayerAI/PlayerAI.cpp
C++
gpl-2.0
57,029
<?php /* * This file is part of SeAT * * Copyright (C) 2015 to 2022 Leon Jacobs * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ namespace Seat\Services\Traits; use Composer\InstalledVersions; use GuzzleHttp\Client; use GuzzleHttp\Exception\GuzzleException; use OutOfBoundsException; use Seat\Services\AbstractSeatPlugin; use stdClass; /** * Trait VersionsManagementTrait. * * @package Seat\Services\Traits */ trait VersionsManagementTrait { /** * Compute a list of provider class which are implementing SeAT package structure. * * @return \stdClass */ protected function getPluginsMetadataList(): stdClass { app()->loadDeferredProviders(); $providers = array_keys(app()->getLoadedProviders()); $packages = (object) [ 'core' => collect(), 'plugins' => collect(), ]; foreach ($providers as $class) { // attempt to retrieve the class from booted app $provider = app()->getProvider($class); if (is_null($provider)) continue; // ensure the provider is a valid SeAT package if (! is_a($provider, AbstractSeatPlugin::class)) continue; // seed proper collection according to package vendor $provider->getPackagistVendorName() === 'eveseat' ? $packages->core->push($provider) : $packages->plugins->push($provider); } return $packages; } /** * @param string $vendor * @param string $package * @return string */ protected function getPackageLatestVersion(string $vendor, string $package): string { // construct the packagist uri to its API $packagist_url = sprintf('https://packagist.org/packages/%s/%s.json', $vendor, $package); try { $installed_version = InstalledVersions::getPrettyVersion(sprintf('%s/%s', $vendor, $package)) ?? '0.0.0'; } catch (OutOfBoundsException $e) { $installed_version = '0.0.0'; } // retrieve package meta-data try { $response = (new Client())->request('GET', $packagist_url); if ($response->getStatusCode() !== 200) return '0.0.0'; // convert the body into an array $json_array = json_decode($response->getBody(), true); // in case we miss either versions or package attribute, return an error as those attribute should contains version information if (! array_key_exists('package', $json_array) || ! array_key_exists('versions', $json_array['package'])) return '0.0.0'; // extract published versions from packagist response $versions = $json_array['package']['versions']; foreach ($versions as $available_version => $metadata) { // ignore any unstable versions if (strpos($available_version, 'dev') !== false || strpos($available_version, 'rc') !== false || strpos($available_version, 'alpha') !== false || strpos($available_version, 'beta') !== false) continue; // return outdated on the first package which is greater than installed version if (version_compare($installed_version, $metadata['version']) < 0) return $metadata['version']; } } catch (GuzzleException $e) { logger()->error($e->getMessage()); return 'offline'; } return $installed_version; } }
eveseat/services
src/Traits/VersionsManagementTrait.php
PHP
gpl-2.0
4,287
<?php if (empty($_REQUEST['feeding'])): $feeding = 0; else: $feeding = $_REQUEST['feeding']; endif; if (empty($_REQUEST['transfer'])): $transfer = 0; else: $transfer = $_REQUEST['transfer']; endif; if (empty($_REQUEST['mobility'])): $mobility = 0; else: $mobility = $_REQUEST['mobility']; endif; if (empty($_REQUEST['dressing'])): $dressing = 0; else: $dressing = $_REQUEST['dressing']; endif; if (empty($_REQUEST['bathing'])): $bathing = 0; else: $bathing = $_REQUEST['bathing']; endif; if (empty($_REQUEST['groming'])): $groming = 0; else: $groming = $_REQUEST['groming']; endif; if (empty($_REQUEST['toilet_use'])): $toilet_use = 0; else: $toilet_use = $_REQUEST['toilet_use']; endif; if (empty($_REQUEST['bowels'])): $bowels = 0; else: $bowels = $_REQUEST['bowels']; endif; if (empty($_REQUEST['bladder'])): $bladder = 0; else: $bladder = $_REQUEST['bladder']; endif; if (empty($_REQUEST['stairs'])): $stairs = 0; else: $stairs = $_REQUEST['stairs']; endif; $score = $feeding + $transfer + $mobility + $dressing + $bathing + $groming + $toilet_use + $bowels + $bladder + $stairs; switch ($score) { case 0: $text = "ติดเตียง (เตียง 3)"; break; case ($score > 12): $text = "ติดสังคม (เตียง 1)"; break; case ($score > 5): $text = "ติดบ้าน (เตียง 2)"; break; case ($score < 5): $text = "ติดเตียง (เตียง 3)"; break; } echo "คะแนนที่ได้ " . $score . " คะแนน (เต็ม 20 คะแนน)<br>" . $text; ?>
kukks205/jhhc
page/old_screen/adl_result.php
PHP
gpl-2.0
1,838
package icaro.pruebas; import icaro.infraestructura.entidadesBasicas.NombresPredefinidos; import icaro.infraestructura.patronAgenteReactivo.control.acciones.AccionSincrona; import icaro.infraestructura.entidadesBasicas.descEntidadesOrganizacion.ComprobadorRutasEntidades; import icaro.infraestructura.entidadesBasicas.interfaces.InterfazGestion; import icaro.infraestructura.recursosOrganizacion.recursoTrazas.ItfUsoRecursoTrazas; import icaro.infraestructura.recursosOrganizacion.recursoTrazas.imp.componentes.InfoTraza; import icaro.infraestructura.recursosOrganizacion.recursoTrazas.imp.componentes.InfoTraza.NivelTraza; import icaro.infraestructura.recursosOrganizacion.repositorioInterfaces.ItfUsoRepositorioInterfaces; import java.util.Vector; /* * Implementacion por defecto de las acciones que se ejecutaron por parte del gestor de agentes. * @author */ public class VerificarExistenciaEntidadesDescripcion extends AccionSincrona { /** * Almacn de los nombres de los agentes que este gestor debe gestionar */ protected Vector<String> nombresAgentesGestionados = new Vector<String>(); /** * Depuracion para pruebas */ protected static boolean DEBUG = true; private InterfazGestion ItfGestionRecTrazas; private ItfUsoRecursoTrazas ItfUsoRecTrazas; // private ItfGestionAgenteReactivo ItfgestGestorInicial = null; // private ItfUsoConfiguracion configuracionExterna = null; // private String identGestorNodo = null; // private String msgUsuario = null; private String rutaDescripcionOrganizacion = null; private String nombreAgente; private ItfUsoRepositorioInterfaces itfUsoRepositorio; /** * Hebra para la monitorizacion */ // private HebraMonitorizacion hebra; // private Thread currentthread; /** * Tiempo de monitorizacion */ protected int tiempoParaNuevaMonitorizacion; protected final static String SUBTIPO_COGNITIVO = "Cognitivo"; protected final static String SUBTIPO_REACTIVO = "Reactivo"; private NombresPredefinidos.TipoEntidad tipoEntidad = NombresPredefinidos.TipoEntidad.Reactivo; /** * Constructor */ public VerificarExistenciaEntidadesDescripcion() { super(); this.nombreAgente = NombresPredefinidos.NOMBRE_INICIADOR; try { itfUsoRepositorio = NombresPredefinidos.REPOSITORIO_INTERFACES_OBJ; ItfUsoRecTrazas = NombresPredefinidos.RECURSO_TRAZAS_OBJ; ItfGestionRecTrazas = (InterfazGestion) this.itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_GESTION + NombresPredefinidos.RECURSO_TRAZAS); // ItfUsoRecTrazas.trazar(this.nombreAgente, "Fichero Descripcion organizacion : "+ // NombresPredefinidos.DESCRIPCION_XML_POR_DEFECTO, NivelTraza.debug); ItfUsoRecTrazas.visualizarIdentFicheroDescrOrganizacion(); ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza(this.nombreAgente, tipoEntidad, "Activacion agente reactivo " + nombreAgente + "\n" + "Fichero Descripcion organizacion : " + NombresPredefinidos.DESCRIPCION_XML_POR_DEFECTO, InfoTraza.NivelTraza.debug)); } catch (Exception e2) { e2.printStackTrace(); } /* * ItfUsoConfiguracion config = * (ItfUsoConfiguracion)RepositorioInterfaces.instance().obtenerInterfaz * (NombresPredefinidos.ITF_USO+NombresPredefinidos.CONFIGURACION); * tiempoParaNuevaMonitorizacion = config.getEntornoEjecucionGestor(nombreAgente). * getIntervaloMonitorizacion().intValue(); */ } @Override public void ejecutar(Object... params) { // Se verifican las rutas donde deben encontrarse las entidades de descripcion: // El esquema de descripcion de la organizacion, el fichero de descripcion y el paquete jaxb // nombreAgente= this.getNombreAgente(); ItfUsoRecTrazas.setIdentAgenteAReportar(this.nombreAgente); ComprobadorRutasEntidades comprobadorRutas = new ComprobadorRutasEntidades(); Boolean SeHapodidoLocalizarEsquema = true; Boolean SeHapodidoLocalizarFicheroDescripcion = true; this.trazas.trazar(nombreAgente, "Verificando la existencia de entidadesDescripcion", NivelTraza.debug); if (!comprobadorRutas.existeSchemaDescOrganizacion()) { ItfUsoRecTrazas .aceptaNuevaTraza(new InfoTraza( "Iniciador", "No se pudo encontrar fichero que define el esquema para interpretar la descripcion de la Organizacion", InfoTraza.NivelTraza.error)); SeHapodidoLocalizarEsquema = false; } rutaDescripcionOrganizacion = comprobadorRutas .buscarDescOrganizacion(NombresPredefinidos.DESCRIPCION_XML_POR_DEFECTO); if (rutaDescripcionOrganizacion == null) { ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", "No se pudo encontrar fichero de descripcion de la Organizacion", InfoTraza.NivelTraza.error)); SeHapodidoLocalizarFicheroDescripcion = false; } try { if (SeHapodidoLocalizarEsquema && SeHapodidoLocalizarFicheroDescripcion) { this.procesarInput("existenEntidadesDescripcion", null); } else { this.procesarInput("errorLocalizacionFicherosDescripcion", null); } } catch (Exception e2) { e2.printStackTrace(); ItfUsoRecTrazas .aceptaNuevaTraza(new InfoTraza( "Iniciador", tipoEntidad, "No se ha podido enviar un evento a si mismo notificando la validacion de las rutas de las entidades de descripcion . ", InfoTraza.NivelTraza.error)); } } public void getInfoObjectInput(Object obj) { } // public void crearRecursosNucleoOrganizacion () throws Exception { // // // Intento crear los recursos en orden pero si se producen errores se capturan, se visualizan // y // // se pude intentar dialogar con el usuario para que los corrija // // try { // // Se crea el recurso de configuración y posteriormente se debería dar orden al recurso // // de trazas para pintar el proceso. // // ItfUsoRepositorioInterfaces repositorioInterfaces = // RepositorioInterfaces.instance(RepositorioInterfaces.IMP_LOCAL); // trazas.trazar(this.nombreAgente,"Creacion de recursos nucleo Organizacion", NivelTraza.info); // configuracionExterna = ClaseGeneradoraConfiguracion.instance(); // // Se crea una configuracion con el fichero de descripcion de la organizacion // // rutaDescripcionOrganizacion // =NombresPredefinidos.RUTA_DESCRIPCIONES+NombresPredefinidos.DESCRIPCION_XML_POR_DEFECTO+".xml"; // configuracionExterna.interpretarDescripOrganizacion(rutaDescripcionOrganizacion); // if(!configuracionExterna.validarDescripOrganizacion()){ // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza(this.nombreAgente, // "Se produjo un error al interpretar el fichero de descripcion de la organizacion", // InfoTraza.NivelTraza.error)); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_InterpretacionDescripcionOrganizacion", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // }else { // // registro la configuracion // itfUsoRepositorio.registrarInterfaz( // NombresPredefinidos.ITF_USO + NombresPredefinidos.CONFIGURACION,configuracionExterna); // // Ahora que la configuracion es correcta , interpreto las propiedades globales // // y pongo la configuracion de trazas definida por el usuario // Boolean ConfiguracionTrazas = false; // if (NombresPredefinidos.ACTIVACION_PANEL_TRAZAS_DEBUG.startsWith("t")){ // ConfiguracionTrazas = true; // } // else // ItfGestionRecTrazas.termina(); // ItfUsoRecTrazas.visualizacionDeTrazas(ConfiguracionTrazas); // // // // Se crea el gestor de Organizacion // // DescInstanciaAgente descGestor = // configuracionExterna.getDescInstanciaGestor(NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); // // creo el agente gestor de organizacion // // // arranco la organizacion // // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "recursosNucleoCreados", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // } // ItfgestGestorOrg.arranca(); // } catch (IllegalArgumentException ie) { // System.err.println("Error. La organizacion no se ha compilado correctamente. Compruebe que los ficheros xml de los automatas se encuentren en el classpath."); // ie.printStackTrace(); // System.exit(1); // // } // catch (ExcepcionEnComponente ie) { // msgUsuario = // "Se produjo un error al interpretar el fichero de descripcion de la organizacion \n"+ // "La ruta especificada es : " + rutaDescripcionOrganizacion; // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // msgUsuario,InfoTraza.NivelTraza.error)); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_InterpretacionDescripcionOrganizacion", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // } // catch (Exception e) { // msgUsuario = // "Se produjo un error al interpretar el fichero de descripcion de la organizacion \n"+ // "La ruta especificada es : " + rutaDescripcionOrganizacion; // System.err.println(msgUsuario); // e.printStackTrace(); // ItfUsoRecTrazas.aceptaNuevaTraza(new // InfoTraza("Iniciador",msgUsuario,InfoTraza.NivelTraza.error)); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_InterpretacionDescripcionOrganizacion", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // } // } // // public String localizarComportamientoGestorInicial ( String identGestor) throws // ExcepcionEnComponente, RemoteException { // // String locComportamientoGestor = null; // // Se obtiene el gestor inicial de la descripción de la organizacion. Puede ser un gestor de // organizacion o un gestor de nodo // // identGestor = configuracionExterna.getIdentGestorInicial(); // try { // // DescComportamientoAgente desCompGestor = // configuracionExterna.getDescComportamientoAgente(identGestor); // DescInstanciaGestor desCompGestor = configuracionExterna.getDescInstanciaGestor(identGestor); // locComportamientoGestor = // desCompGestor.getDescComportamiento().getLocalizacionComportamiento(); // if ( identGestor.startsWith(NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)){ // if (locComportamientoGestor.isEmpty()) // locComportamientoGestor = NombresPredefinidos.PAQUETE_GESTOR_ORGANIZACION; // // } else // if ( identGestorNodo.startsWith(NombresPredefinidos.NOMBRE_GESTOR_NODO)){ // // identGestorACrear = NombresPredefinidos.NOMBRE_GESTOR_NODO; // if (locComportamientoGestor.isEmpty()) // locComportamientoGestor = NombresPredefinidos.COMPORTAMIENTO_PORDEFECTO_GESTOR_NODO; // } // else{ // // El gestor inicial debe ser un gestor de organización o un gestor de nodo y no se ha // definido ninguno // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "No se pudo crear el comportamiento del Gestor Inicial porque no hay un Gestor de Organizacion o un Gestor de Nodo definido." // + " Revisar el fichero de Descripcion de la Organizacion", // InfoTraza.NivelTraza.error)); // // } // // } catch (ExcepcionEnComponente ex) { // Logger.getLogger(VerificarExistenciaEntidadesDescripcion.class.getName()).log(Level.SEVERE, // null, ex); // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "No se pudo crear el comportamiento del Gestor Inicial porque no se pudo obtener el comportamiento del Gestor de Organizacion o del Gestor de Nodo definido." // + " Revisar el fichero de Descripcion de la Organizacion", // InfoTraza.NivelTraza.error)); // } // return locComportamientoGestor; // } // public void crearGestorInicial () throws Exception { // // String locComportamientoGestor = null; // // Se obtiene el gestor inicial de la descripción de la organizacion. Puede ser un gestor de // organizacion o un gestor de nodo // // identGestorNodo = configuracionExterna.getIdentGestorInicial(); // if (configuracionExterna.despliegueOrgEnUnSoloNodo()) // identGestorNodo = NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION; // else { // Si la organizacion es distribuida el iniciador mira si esta en el nodo del GO o en // otro nodo // String identNodoGO = // configuracionExterna.getHostComponente(NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); // String thisHost = InetAddress.getLocalHost().getHostName(); // if ( thisHost.equalsIgnoreCase(identNodoGO)) // Esta en el nodo del GO se crea un Gestor de // Organizacion // identGestorNodo = NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION; // else identGestorNodo = NombresPredefinidos.NOMBRE_GESTOR_NODO; // Se crea un Gestor de Nodo // } // // // if ( identGestorNodo.startsWith(NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)){ // //// identGestorACrear = NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION; // // // // // //// locComportamientoGestor = // NombresPredefinidos.COMPORTAMIENTO_PORDEFECTO_GESTOR_ORGANIZACION; // // locComportamientoGestor = // configuracionExterna.getDescComportamientoAgente(NombresPredefinidos.COMPORTAMIENTO_PORDEFECTO_GESTOR_ORGANIZACION).getLocalizacionComportamiento(); // // // // } else // // if ( identGestorNodo.startsWith(NombresPredefinidos.NOMBRE_GESTOR_NODO)){ // //// identGestorACrear = NombresPredefinidos.NOMBRE_GESTOR_NODO; // // locComportamientoGestor = NombresPredefinidos.COMPORTAMIENTO_PORDEFECTO_GESTOR_NODO; // // } // // else{ // // // El gestor inicial debe ser un gestor de organización o un gestor de nodo y no se ha // definido ninguno // // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // // // "No se pudo crear el comportamiento del Gestor Inicial porque no hay un Gestor de Organizacion o un Gestor de Nodo definido." // // + " Revisar el fichero de Descripcion de la Organizacion", // // InfoTraza.NivelTraza.error)); // // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // // "error_al_crearGestorInicial", // // NombresPredefinidos.NOMBRE_INICIADOR, // // NombresPredefinidos.NOMBRE_INICIADOR)); // // } // locComportamientoGestor = this.localizarComportamientoGestorInicial(identGestorNodo); // // if (!locComportamientoGestor.isEmpty() ) { // // Se crea el gestor y se registra en el registro RMI en el caso en que la organizacion sea // distribuida // try { // // FactoriaAgenteReactivo.instancia().crearAgenteReactivo(identGestorNodo // ,locComportamientoGestor); // DescInstanciaGestor desCompGestor = // configuracionExterna.getDescInstanciaGestor(identGestorNodo); // FactoriaAgenteReactivo.instancia().crearAgenteReactivo(desCompGestor); // ItfgestGestorInicial = (ItfGestionAgenteReactivo) itfUsoRepositorio.obtenerInterfaz( // NombresPredefinidos.ITF_GESTION + identGestorNodo); // // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "GestorInicialCreado", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // // } // catch (ExcepcionEnComponente ie) { // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "No se pudo crear el comportamiento del Gestor inicial", // InfoTraza.NivelTraza.error)); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_al_crearGestorInicial", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // } // catch (Exception e) { // System.err.println("Error. No se ha podido crear o registrar el Gestor Inicial."); // e.printStackTrace(); // } // } // } // // public void crearGestorOrganizacion () throws Exception { // try { // FactoriaAgenteReactivo.instancia().crearAgenteReactivo(NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION // ,NombresPredefinidos.COMPORTAMIENTO_PORDEFECTO_GESTOR_ORGANIZACION); // ItfgestGestorInicial = (ItfGestionAgenteReactivo) itfUsoRepositorio.obtenerInterfaz( // NombresPredefinidos.ITF_GESTION + NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); // // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "GestorOrganizacionCreado", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // // } // catch (ExcepcionEnComponente ie) { // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "No se pudo crear el comportamiento del Gestor de Organizacion", // InfoTraza.NivelTraza.error)); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_al_crearGestorInicial", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // // } // catch (Exception e) { // System.err.println("Error. No se ha podido crear o registrar el Gestor de Organizacion."); // e.printStackTrace(); // } // } // // /** // * arranca los agentes que se especifiquen en la config. // */ // public void arrancarGestorInicialyTerminar()throws Exception { // logger.debug("GestorIniciador: Arrancando gestor Inicial."); // // try { // // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "Arrancando el Gestor Inicial . ", InfoTraza.NivelTraza.debug)); // // if (ItfgestGestorInicial != null ){ // // arranca el Gestor de Organizacion y Termina el iniciador // this. ItfgestGestorInicial.arranca(); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "GestorInicial_arrancado_ok", // nombreAgente, // nombreAgente)); // // // terminarPorPropiaVoluntad(); // // } // else { // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "La interfaz del GO es nula . ", InfoTraza.NivelTraza.error)); // // genero un evento interno de error // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_al_arrancarGestorOrganizacion", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // } // } catch (Exception e2) { // e2.printStackTrace(); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_al_arrancarGestorInicial", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "No se ha podido arrancar el Gestor de Organizacion . ", InfoTraza.NivelTraza.error)); // // } // // } // // /** // * Devuelve cierto si es necesario arrancar el agente // * // * @param nombreAgente // * @return // */ // /* // * private boolean esNecesarioArrancar(String nombreAgente) { Enumeration // * enume = configEspecifica.getListaAgentes().enumerateAgente(); while // * (enume.hasMoreElements()) { Agente item = (Agente)enume.nextElement(); if // * (nombreAgente.equals(item.getNombre())) return // * item.getHayQueArrancarlo(); } logger.error("GestorAgentes: No se encontr� // * ning�n agente con nombre "+nombreAgente+" dentro de la lista de objetos // * gestionados."); throw new NullPointerException(); } // */ // /** // * Decide que hacer en caso de fallos en los agentes. // */ // public void decidirTratamientoErrorIrrecuperable() { // // el tratamiento ser� siempre cerrar todo el chiringuito // logger.debug("GestorAgentes: Se decide cerrar el sistema ante un error critico irrecuperable."); // try { // // trazas.aceptaNuevaTraza(new InfoTraza( // this.nombreAgente, // "Se decide cerrar el sistema ante un error critico irrecuperable.", // InfoTraza.NivelTraza.debug)); // } catch (Exception e2) { // e2.printStackTrace(); // } // try { // // trazas.aceptaNuevaTraza(new InfoTraza( // nombreAgente, // "Terminado proceso de arranque automatico de agentes.", // InfoTraza.NivelTraza.debug)); // } catch (Exception e2) { // e2.printStackTrace(); // } // // try { // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "tratamiento_terminar_agentes_y_gestor_agentes", // nombreAgente, // nombreAgente)); // } catch (Exception e) { // e.printStackTrace(); // } // } // // /** // * intenta arrancar los agentes que especifique la config y hayan dado // * problemas. // */ // public void recuperarErrorArranqueAgentes() { // // por defecto no se implementan pol�ticas de recuperaci�n // //logger.debug("GestorAgentes: Fue imposible recuperar el error en el arranque de los agentes."); // try { // // trazas.aceptaNuevaTraza(new InfoTraza( // nombreAgente, // "Fue imposible recuperar el error en el arranque de los agentes.", // InfoTraza.NivelTraza.debug)); // } catch (Exception e2) { // e2.printStackTrace(); // } // try { // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "imposible_recuperar_arranque", // nombreAgente, // nombreAgente)); // } catch (Exception e) { // e.printStackTrace(); // } // } // // /** // * Elabora un informe del estado en el que se encuentran los agentes y lo // * env�a al sistema de trazas. // */ // public void generarInformeErrorIrrecuperable() { // // Producimos traza de un error // logger.error("GestorIniciador: Se ha producido un error irrecuperable."); // try { // trazas.aceptaNuevaTraza(new InfoTraza( // "Iniciador", // " Iniciador a la espera de terminacion por parte del usuario debido a un error irrecuperable.", // InfoTraza.NivelTraza.error)); // this.informaraMiAutomata("informe_generado", null); // } catch (Exception e2) { // e2.printStackTrace(); // } // /* // try { // this.itfUsoGestorAReportar.aceptaEvento(new EventoRecAgte( // "error_en_arranque_gestores", // NombresPredefinidos.NOMBRE_GESTOR_RECURSOS, // NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte("informe_generado", // nombreAgente, // nombreAgente)); // } catch (Exception e) { // e.printStackTrace(); // } // */ // } // // // /** // * Crea y arranca un agente. Es necesario pasar las caracter�sticas del // * agente a crear por par�metro. // */ // public void crearAgente() { // // esto hay que recuperarlo de los parametros // // logger.debug("GestorAgentes: crearAgente():Este metodo no esta implementado"); // try { // // trazas.aceptaNuevaTraza(new InfoTraza( // nombreAgente, // "crearAgente():Este metodo no esta implementado", // InfoTraza.NivelTraza.debug)); // } catch (Exception e2) { // e2.printStackTrace(); // } // throw new UnsupportedOperationException(); // } // // /** // * Monitoriza secuencialmente todos los agentes activos que est�n definidos // * como necesarios en la configuraci�n. // */ // public void monitorizarAgentes() { // // if(DEBUG) System.out.println("GestorAgentes:Comienza ciclo // // monitorizaci�n."); // // boolean errorEncontrado = false; // // recuperar todos los interfaces de gesti�n del repositorio que estamos // // gestionando // Enumeration enume = nombresAgentesGestionados.elements(); // while (enume.hasMoreElements() && !errorEncontrado) { // String nombre = (String) enume.nextElement(); // // if(DEBUG) System.out.println("GestorAgentes:Monitorizando agente // // "+nombre+"."); // // recupero el interfaz de gestion del repositorio // try { // InterfazGestion itfGes = (InterfazGestion) // this.itfUsoRepositorio.obtenerInterfaz(NombresPredefinidos.ITF_GESTION + nombre); // int monitoriz = itfGes.obtenerEstado(); // if (monitoriz == InterfazGestion.ESTADO_ERRONEO_IRRECUPERABLE || monitoriz == // InterfazGestion.ESTADO_ERRONEO_RECUPERABLE || monitoriz == InterfazGestion.ESTADO_TERMINADO // || monitoriz == InterfazGestion.ESTADO_TERMINANDO) { // errorEncontrado = true; // logger.debug("GestorAgentes:Agente " + nombre + " est� en estado err�neo o terminado."); // try { // ItfUsoRecursoTrazas trazas = (ItfUsoRecursoTrazas) // ClaseGeneradoraRepositorioInterfaces.instance().obtenerInterfaz( // NombresPredefinidos.ITF_USO + NombresPredefinidos.RECURSO_TRAZAS); // trazas.aceptaNuevaTraza(new InfoTraza( // this.nombreAgente, // "Agente " + nombre + " esta en estado erroneo o terminado.", // InfoTraza.NivelTraza.debug)); // } catch (Exception e2) { // e2.printStackTrace(); // } // } // /* // * else if(DEBUG) System.out.println("GestorAgentes:Agente // * "+nombre+" est� ok."); // */ // } catch (Exception ex) { // errorEncontrado = true; // logger.error("GestorAgentes: No se pudo acceder al repositorio."); // ex.printStackTrace(); // } // } // // if (errorEncontrado) { // try { // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_al_monitorizar", // nombreAgente, // nombreAgente)); // } catch (Exception e) { // e.printStackTrace(); // } // } else { // try { // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte("agentes_ok", // nombreAgente, // nombreAgente)); // } catch (Exception e) { // e.printStackTrace(); // } // } // } // // // /** // * Intenta recuperar los errores detectados en la monitorizaci�n siguiendo // * la pol�tica definida para cada agente. // */ // // // /** // * destruye los recursos que se crearon a lo largo del ciclo de vida de este // * agente. // */ // public void terminarPorPropiaVoluntad() throws Exception, Throwable { // // termina el gestor. // // puede esperarse a que terminen los agentes // //logger.debug("GestorAgentes: Terminando gestor de agentes."); // logger.debug("Iniciador: Terminando gestor de la organizacion y los recursos de la infraestructura."); // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "Terminando el Iniciador.", // InfoTraza.NivelTraza.debug)); // try { // // se obtiene la propia interfaz de gestion para terminar // // // ItfgestGestorInicial.termina(); // // // ((ItfGestionAgenteReactivo) this.itfUsoRepositorio // .obtenerInterfaz(NombresPredefinidos.ITF_GESTION // + this.nombreAgente)) // .termina(); // // quitamos las interfaces del repositorio de interfaces // itfUsoRepositorio.eliminarRegistroInterfaz(NombresPredefinidos.ITF_USO+this.nombreAgente); // itfUsoRepositorio.eliminarRegistroInterfaz(NombresPredefinidos.ITF_GESTION+this.nombreAgente); // // definimos el gestor al que debe enviar los eventos el RC // ItfUsoRecTrazas.setIdentAgenteAReportar(this.identGestorNodo); // // // // this.itfUsoPropiadeEsteAgente.aceptaEvento(new // // EventoRecAgte ("termina",this.nombreAgente,this.nombreAgente)); // // } catch (Exception ex) { // ex.printStackTrace(); // } // logger.debug("Iniciador: Terminando."); // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "Terminando.", // InfoTraza.NivelTraza.debug)); // if (this.hebra != null) // this.hebra.finalizar(); // // this.currentthread.join(); // } // public void procesarPeticionTerminacion() { // logger.debug("Iniciador: Procesando la peticion de terminacion"); // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "Procesando la peticion de terminacion", // InfoTraza.NivelTraza.debug)); // // ItfUsoRecTrazas.pedirConfirmacionTerminacionAlUsuario(); // // /*try { // // this.itfUsoAgente.aceptaEvento(new // // EventoRecAgte("termina",null,null)); // // // ItfGestionAgenteReactivo gestion = (ItfGestionAgenteReactivo) this.itfUsoRepositorio // .obtenerInterfaz(NombresPredefinidos.ITF_GESTION // + NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); // gestion.termina(); // } catch (Exception e) { // e.printStackTrace(); // } // */ // } // // public void comenzarTerminacionConfirmada() { // logger.debug("Iniciador: Terminando recursos..."); // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "Comenzando la terminacion de los recursos...", // InfoTraza.NivelTraza.info)); // // // try { // // ItfGestionRecTrazas.termina(); // // y a continuacion se termina el gestor // // terminarPorPropiaVoluntad();if (this.hebra != null) // if (this.hebra != null) // this.hebra.finalizar(); // System.exit(0); // } catch (Exception ex) { // Logger.getLogger(VerificarExistenciaEntidadesDescripcion.class.getName()).log(Level.SEVERE, // null, ex); // } catch (Throwable ex) { // Logger.getLogger(VerificarExistenciaEntidadesDescripcion.class.getName()).log(Level.SEVERE, // null, ex); // } // // // } // // public void clasificaError() { // } }
palomagc/MovieChatter
src/icaro/pruebas/VerificarExistenciaEntidadesDescripcion.java
Java
gpl-2.0
27,852
<?php require 'head.php';?> <div class="container-fluid main-container"> <div class="col-md-2 sidebar"> <div class="row"> <!-- uncomment code for absolute positioning tweek see top comment in css --> <div class="absolute-wrapper"> </div> <!-- Menu --> <div class="side-menu"> <nav class="navbar navbar-default" role="navigation"> <!-- Main Menu --> <div class="side-menu-container"> <ul class="nav navbar-nav"> <li class="active"><a href="#" target="_self"><span class="glyphicon glyphicon-dashboard"></span> Dashboard</a></li> <li><a href="grafik.php"><span class="glyphicon glyphicon-signal"></span> Link</a></li> </ul> </div><!-- /.navbar-collapse --> </nav> </div> </div> </div> <div class="col-md-10 content"> <div class="panel panel-default"> <div class="panel-heading"> Dashboard </div> <div class="panel-body"> <?php require 'addcalon.php'; ?> </div> </div> </div> <?php require'foot.php';?>
zona284/evotemipa
admin/admin.php
PHP
gpl-2.0
998
/* This file is part of Work in Texas (WIT) Search Helper. WIT Search Helper is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. WIT Search Helper is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with WIT Search Helper. If not, see <http://www.gnu.org/licenses/>. */ /* functions for getting and setting correct value from local storage local storage key: WITStorage array structure: see function getNewLocStorArray below */ function getLocalStorage(loc) { arr = testLocalStorageIntegrity(); if(loc == 'maxDist') return arr[0].maxDist; else if(loc == 'myZip') return arr[0].myZip; else if(loc == 'resultHandling') return arr[0].resultHandling; else if(loc == 'myDistances') return arr[0].myDistances; else window.console.log('Nothing returned for ' + loc); } //arrAdd array structure: [value to add, key to add to] function setLocalStorage(arrAdd) { arr = testLocalStorageIntegrity(); for (i = 0; i < arrAdd.length; i++) { var val = arrAdd[i][0]; var loc = arrAdd[i][1]; if(loc == 'maxDist') arr[0].maxDist = val; else if(loc == 'myZip') arr[0].myZip = val; else if(loc == 'resultHandling') arr[0].resultHandling = val; else if(loc == 'myDistances') arr[0].myDistances = val; } localStorage['WITStorage'] = JSON.stringify(arr); return; } function testLocalStorageIntegrity() { var arr = localStorage['WITStorage']; if(arr == 'undefined' || arr == null) { //empty or error, redo storage // lOut('Redoing Array'); return getNewLocStorArray(); } arr = JSON.parse(arr); if(arr.length != 4) { //empty or error, redo storage // lOut('Redoing Array'); return getNewLocStorArray(); } //no problems, return good local storage values return arr; } //SET DEFAULT VALUES HERE, ALL VALUES ARE PRELOADED FROM THIS ARRAY function getNewLocStorArray() { var myArray = [ {"maxDist":"20"}, {"myZip":"76010"}, {"resultHandling":""}, {"myDistances":""} ] return myArray; } //shortened script for printing to console log function lOut(str) { window.console.log(str); } //functions for testing time to execute scripts function myTime(a) { i = performance.now(); lOut(a[0] + ". " + (i-a[1])); a[0]++; a[1] = i; return a; }
Soscan2062/wit-search-helper
utils.js
JavaScript
gpl-2.0
2,653
# -*- coding: utf-8 -*- import sys sys.path.append(sys.argv[1]) from scriptlib import * """Файлы пакета""" FILES = ( '7z920-x64.msi', '7z920.msi' ) """Имена исполняемых файлов""" if ARCH == '64': INSTALLER = os.path.join('', DIR, FILES[0]) else: INSTALLER = os.path.join('', DIR, FILES[1]) def install(): run_msi('/i', INSTALLER) def remove(): run_msi('/x', INSTALLER) check_files(FILES) if ACTION == 'install': install() elif ACTION == 'remove': remove()
kuchiman/wpm-pkg
7zip/script.py
Python
gpl-2.0
529
/* ============================================================ * * This file is a part of kipi-plugins project * http://www.kipi-plugins.org * * Date : 2003-10-14 * Description : batch image rotation * * Copyright (C) 2003-2005 by Renchi Raju <renchi@pooh.tam.uiuc.edu> * Copyright (C) 2004-2009 by Marcel Wiesweg <marcel dot wiesweg at gmx dot de> * Copyright (C) 2006-2009 by Gilles Caulier <caulier dot gilles at gmail dot com> * * This program is free software; you can redistribute it * and/or modify it under the terms of the GNU General * Public License as published by the Free Software Foundation; * either version 2, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * ============================================================ */ #define XMD_H // C++ includes. #include <cstdio> // C ANSI includes. extern "C" { #include <sys/types.h> #include <unistd.h> #include <jpeglib.h> } // Qt includes. #include <QFile> #include <QFileInfo> // KDE includes. #include <kprocess.h> #include <kdebug.h> #include <klocale.h> // Local includes. #include "utils.h" #include "transupp.h" #include "jpegtransform.h" #include "imagerotate.h" #include "imagerotate.moc" namespace KIPIJPEGLossLessPlugin { ImageRotate::ImageRotate() : QObject() { m_tmpFile.setSuffix("kipiplugin-rotate"); m_tmpFile.setAutoRemove(true); } ImageRotate::~ImageRotate() { } bool ImageRotate::rotate(const QString& src, RotateAction angle, QString& err, bool updateFileTimeStamp) { QFileInfo fi(src); if (!fi.exists() || !fi.isReadable() || !fi.isWritable()) { err = i18n("Error in opening input file"); return false; } if ( !m_tmpFile.open() ) { err = i18n("Error in opening temporary file"); return false; } QString tmp = m_tmpFile.fileName(); if (Utils::isRAW(src)) { err = i18n("Cannot rotate RAW file"); return false; } else if (Utils::isJPEG(src)) { if (!rotateJPEG(src, tmp, angle, err, updateFileTimeStamp)) { if (err == "nothing to do") { err=QString::null; return true; } return false; } } else { // B.K.O #123499 : we using Image Magick API here instead QT API // else TIFF/PNG 16 bits image are broken! if (!rotateImageMagick(src, tmp, angle, err)) return false; // We update metadata on new image. Utils tools(this); if (!tools.updateMetadataImageMagick(tmp, err)) return false; } // Move back to original file if (!Utils::MoveFile(tmp, src)) { err = i18n("Cannot update source image"); return false; } return true; } bool ImageRotate::rotateJPEG(const QString& src, const QString& dest, RotateAction angle, QString& err, bool updateFileTimeStamp) { Matrix transform=Matrix::none; switch(angle) { case (Rot90): { transform = Matrix::rotate90; break; } case (Rot180): { transform = Matrix::rotate180; break; } case (Rot270): { transform = Matrix::rotate270; break; } case (Rot0): { transform = Matrix::none; break; } default: { kError( 51000 ) << "ImageRotate: Nonstandard rotation angle" << endl; err = i18n("Nonstandard rotation angle"); return false; } } return transformJPEG(src, dest, transform, err, updateFileTimeStamp); } bool ImageRotate::rotateImageMagick(const QString& src, const QString& dest, RotateAction angle, QString& err) { KProcess process; process.clearProgram(); process << "convert"; process << "-rotate"; switch(angle) { case (Rot90): { process << "90"; break; } case (Rot180): { process << "180"; break; } case (Rot270): { process << "270"; break; } case (Rot0): { break; } default: { kError( 51000 ) << "ImageRotate: Nonstandard rotation angle" << endl; err = i18n("Nonstandard rotation angle"); return false; } } process << src + QString("[0]") << dest; kDebug( 51000 ) << "ImageMagick Command line: " << process.program() << endl; process.start(); if (!process.waitForFinished()) return false; if (process.exitStatus() != QProcess::NormalExit) return false; switch (process.exitCode()) { case 0: // Process finished successfully ! { return true; break; } case 15: // process aborted ! { return false; break; } } // Processing error ! m_stdErr = process.readAllStandardError(); err = i18n("Cannot rotate: %1", m_stdErr.replace('\n', ' ')); return false; } } // namespace KIPIJPEGLossLessPlugin
ruphy/kipi-plugins
jpeglossless/imagerotate.cpp
C++
gpl-2.0
5,473
package org.mo.game.editor.core.entity.common; import org.mo.game.editor.core.entity.base.XBaseEntityItemTemplate; public class XEntityItemTemplate extends XBaseEntityItemTemplate{ private static final long serialVersionUID = 1L; }
favedit/MoPlatform
mo-gm-develop/src/editor-java/org/mo/game/editor/core/entity/common/XEntityItemTemplate.java
Java
gpl-2.0
245
package data; import java.io.File; import java.io.FileReader; import java.util.HashMap; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; /** * This class contains all different types of incidents that can arrive. * * @author Alexandre Fourgs * */ public class IncidentDatabase { private static IncidentDatabase INSTANCE = new IncidentDatabase(); private HashMap<Integer, IncidentData> incidentDatabase = new HashMap<Integer, IncidentData>(); private IncidentDatabase(){ incidentDatabase = incidentParsing(); } /** * Parses the .json file of incident and create a HashMap containing parsed data. * * @return a HashMap object that contains all types of incident & informations about it. * */ private HashMap<Integer, IncidentData> incidentParsing(){ HashMap<Integer, IncidentData> incidentDatabase = new HashMap<Integer, IncidentData>(); File json = new File("data/incident.json"); JSONParser fileParser = new JSONParser(); try { Object obj = fileParser.parse(new FileReader(json)); JSONObject jsonObject = (JSONObject) obj ; JSONArray schedulesArray = (JSONArray) jsonObject.get("Incident"); Iterator it = schedulesArray.iterator(); while (it.hasNext()) { JSONObject innerObj = (JSONObject) it.next(); int id = Integer.parseInt((String) innerObj.get("Id")); IncidentData actual = new IncidentData(id, (String)innerObj.get("Type"), Integer.parseInt((String) innerObj.get("Min_Time")), Integer.parseInt((String) innerObj.get("Max_Time"))); incidentDatabase.put(id, actual); } } catch (Exception e){ e.printStackTrace(); } return incidentDatabase ; } /** * Getter of the current initialized instance of IncidentDatabase * @return the initialized instance of IncidentDatabase */ public static IncidentDatabase getInstance(){ return INSTANCE ; } public HashMap<Integer, IncidentData> getIncidentDatabase(){ return incidentDatabase ; } }
Uinelj/logirail
src/data/IncidentDatabase.java
Java
gpl-2.0
2,182
/* A useful and efficient way to use compile-time recursion, partial template specialization and variadic template parameter pack by rangerprice, alias absorbement. */ template <typename Val, typename Type, typename...Args> inline void push(const std::pair<const Val, Type> var, const Args&...args) noexcept { const void* const valueptr = &var.first; operations[var.second](valueptr); nb_param++; push(args...); }; void push() const noexcept { }; template <typename...Args> void call(const std::string & fname, const Args&...args) noexcept { lua_settop(context, 0); lua_getglobal(context, fname.c_str()); push(args...); lua_call(context, nb_param, LUA_MULTRET); };
rangerprice/simplified-lua-api
source/template/slacore.tpl.cpp
C++
gpl-2.0
697
/* * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.retest.swingset3.demos.spinner; import javax.swing.*; import java.awt.*; /** * Arranges labels and spinners into two vertical columns. Labels at the left, spinners at the right. * * @author Mikhail Lapshin */ //<snip>Helpful component for layout of labeled spinners public class JSpinnerPanel extends JPanel { private final JPanel labelPanel; private final JPanel spinnerPanel; public JSpinnerPanel() { setLayout( new BoxLayout( this, BoxLayout.X_AXIS ) ); labelPanel = new JPanel(); labelPanel.setLayout( new GridLayout( 0, 1 ) ); spinnerPanel = new JPanel(); spinnerPanel.setLayout( new GridLayout( 0, 1 ) ); add( labelPanel ); add( Box.createHorizontalStrut( 5 ) ); add( spinnerPanel ); } public void addSpinner( String labelText, JSpinner spinner ) { JLabel label = new JLabel( labelText ); label.setHorizontalAlignment( SwingConstants.TRAILING ); labelPanel.add( label ); JPanel flowPanel = new JPanel(); flowPanel.setLayout( new FlowLayout( FlowLayout.LEADING, 5, 1 ) ); flowPanel.add( spinner ); spinnerPanel.add( flowPanel ); } } //</snip>
retest/swingset3
src/org/retest/swingset3/demos/spinner/JSpinnerPanel.java
Java
gpl-2.0
2,708
<?php /*download sample.csv*/ $csvfilepath = get_option( 'home' ) ."/wp-content/themes/".get_option( 'template' )."/sample_csv.csv"; header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header("Content-Type: image/png"); header("Content-type: application/force-download"); header('Content-Disposition: inline; filename="sample_csv.csv"'); header('Content-Transfer-Encoding: binary'); readfile($csvfilepath); exit; ?>
epgmedia/thunderpress-calendar
wp-content/themes/Events/library/includes/csvdl.php
PHP
gpl-2.0
488
class BadgeGrouping < ActiveRecord::Base GettingStarted = 1 Community = 2 Posting = 3 TrustLevel = 4 Other = 5 has_many :badges end # == Schema Information # # Table name: badge_groupings # # id :integer not null, primary key # name :string(255) not null # description :string(255) not null # position :integer not null # created_at :datetime # updated_at :datetime #
zoubeiri/discourse-snowboard
app/models/badge_grouping.rb
Ruby
gpl-2.0
438
#region Header // Vorspire _,-'/-'/ ProfileRankOrder.cs // . __,-; ,'( '/ // \. `-.__`-._`:_,-._ _ , . `` // `:-._,------' ` _,`--` -: `_ , ` ,' : // `---..__,,--' (C) 2016 ` -'. -' // # Vita-Nex [http://core.vita-nex.com] # // {o)xxx|===============- # -===============|xxx(o} // # The MIT License (MIT) # #endregion namespace VitaNex.Modules.AutoPvP { public enum PvPProfileRankOrder { None, Points, Wins, Kills } }
Andries1985/Shards-of-Nagash
Scripts/VitaNex/Core/Modules/AutoPVP/Objects/Profile/ProfileRankOrder.cs
C#
gpl-2.0
507
<?php /** * The template for displaying the footer * * Contains the closing of the "site-content" div and all content after. * * @package WordPress * @subpackage Twenty_Fifteen * @since Twenty Fifteen 1.0 */ ?> <footer class="bmg-l-footer"> <div class="bmg-l-footer__inner"> <div class="bmg-l-footer__nav"> <div class="bmg-l-footer__country"> <ul> <li> <a class="bmg-l-footer__flag js-user-location-modal" href="javascript:void(0);"> <img width="18" src="/assets/images/flag/phl-a2a1a5476b.png" alt="Philippines">Philippines </a> </li> <li> $USD <a class="bmg-l-footer__country-edit js-user-location-modal" href="javascript:void(0);">EDIT</a> </li> </ul> </div> <nav class="verticalmenu"> <ul> <li> <a href="/aboutbuyma/">About BUYMA</a> </li> <li> <a target="_blank" href="https://buyma-us.zendesk.com/">FAQ</a> </li> <li> <a href="/contact/">Contact us</a> </li> </ul> <ul> <li><a href="/terms/">Terms of Use</a></li> <li><a href="/privacy/">Privacy Policy</a></li> <li><a href="/notice_and_takedown/">Notice and Takedown Policy</a></li> <li><a href="/tradelaw/">Mark based on specific trade law</a></li> <li> <a target="_blank" href="http://www.enigmo.co.jp/en/">enigmo</a> </li> </ul> </nav> </div> <p class="footer-tagline">BUYMA - A new online personal shopping experience</p> <div class="bmg-l-footer__outer-nav"> <nav> <ul> <li> <a target="_blank" href="http://www.buyma.com/">BUYMA.com (JP)</a> </li> <li> <a target="_blank" href="http://buymakorea.com/pages/?">BUYMA Korea</a> </li> <li> <a target="_blank" href="https://stylehaus.jp/">STYLE HAUS</a> </li> <li> <a target="_blank" href="https://www.stulio.jp/">STULIO</a> </li> <li> <a target="_blank" href="http://www.buymabooks.com/">BUYMA Books</a> </li> <li> <a target="_blank" href="http://toptip.jp/">toptip</a> </li> </ul> </nav> <p> <small>©2005 Enigmo Inc. All rights reserved.</small> </p> </div> </div> </footer> <?php wp_footer(); ?> </body> </html>
goygoybords/buyma
wp-content/themes/twentyfifteen/footer.php
PHP
gpl-2.0
2,372
<?php /** * The template for displaying all pages. * * This is the template that displays all pages by default. * Please note that this is the WordPress construct of pages * and that other 'pages' on your WordPress site will use a * different template. * * @package Monaco */ get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'page' ); ?> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || '0' != get_comments_number() ) : comments_template(); endif; ?> <?php endwhile; // end of the loop. ?> </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?>
techborder/wp
wp-content/themes/monaco/page.php
PHP
gpl-2.0
849
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "common/system.h" #include "titanic/sound/qmixer.h" #include "titanic/titanic.h" namespace Titanic { QMixer::QMixer(Audio::Mixer *mixer) : _mixer(mixer) { } bool QMixer::qsWaveMixInitEx(const QMIXCONFIG &config) { assert(_channels.empty()); assert(config.iChannels > 0 && config.iChannels < 256); _channels.resize(config.iChannels); return true; } void QMixer::qsWaveMixActivate(bool fActivate) { // Not currently implemented in ScummVM } int QMixer::qsWaveMixOpenChannel(int iChannel, QMixFlag mode) { // Not currently implemented in ScummVM return 0; } int QMixer::qsWaveMixEnableChannel(int iChannel, uint flags, bool enabled) { // Not currently implemented in ScummVM return 0; } void QMixer::qsWaveMixCloseSession() { _mixer->stopAll(); _channels.clear(); } void QMixer::qsWaveMixFreeWave(Audio::SoundHandle &handle) { _mixer->stopHandle(handle); } void QMixer::qsWaveMixFlushChannel(int iChannel, uint flags) { if (flags & QMIX_OPENALL) { // Ignore channel, and flush all the channels for (uint idx = 0; idx < _channels.size(); ++idx) qsWaveMixFlushChannel(idx, 0); } else { // Flush the specified channel Common::List<SoundEntry>::iterator i; Common::List<SoundEntry> &sounds = _channels[iChannel]._sounds; for (i = sounds.begin(); i != sounds.end(); ++i) _mixer->stopHandle((*i)._soundHandle); sounds.clear(); } } void QMixer::qsWaveMixSetPanRate(int iChannel, uint flags, uint rate) { ChannelEntry &channel = _channels[iChannel]; channel._panRate = rate; channel._volumeChangeStart = channel._volumeChangeEnd = 0; } void QMixer::qsWaveMixSetVolume(int iChannel, uint flags, uint volume) { ChannelEntry &channel = _channels[iChannel]; // QMixer volumes go from 0-32767, but we need to convert to 0-255 for ScummVM assert(volume <= 32767); byte newVolume = (volume >= 32700) ? 255 : volume * 255 / 32767; channel._volumeStart = channel._volume; channel._volumeEnd = newVolume; channel._volumeChangeStart = g_system->getMillis(); channel._volumeChangeEnd = channel._volumeChangeStart + channel._panRate; debugC(DEBUG_DETAILED, kDebugCore, "qsWaveMixSetPanRate vol=%d to %d, start=%u, end=%u", channel._volumeStart, channel._volumeEnd, channel._volumeChangeStart, channel._volumeChangeEnd); } void QMixer::qsWaveMixSetSourcePosition(int iChannel, uint flags, const QSVECTOR &position) { ChannelEntry &channel = _channels[iChannel]; // Flag whether distance should reset when a new sound is started channel._resetDistance = (flags & QMIX_USEONCE) != 0; // Currently, we only do a basic simulation of spatial positioning by // getting the distance, and proportionately reducing the volume the // further away the source is channel._distance = sqrt(position.x * position.x + position.y * position.y + position.z * position.z); } void QMixer::qsWaveMixSetPolarPosition(int iChannel, uint flags, const QSPOLAR &position) { ChannelEntry &channel = _channels[iChannel]; // Flag whether distance should reset when a new sound is started channel._resetDistance = (flags & QMIX_USEONCE) != 0; // Currently, we only do a basic simulation of spatial positioning by // getting the distance, and proportionately reducing the volume the // further away the source is channel._distance = position.range; } void QMixer::qsWaveMixSetListenerPosition(const QSVECTOR &position, uint flags) { // Not currently implemented in ScummVM } void QMixer::qsWaveMixSetListenerOrientation(const QSVECTOR &direction, const QSVECTOR &up, uint flags) { // Not currently implemented in ScummVM } void QMixer::qsWaveMixSetDistanceMapping(int iChannel, uint flags, const QMIX_DISTANCES &distances) { // Not currently implemented in ScummVM } void QMixer::qsWaveMixSetFrequency(int iChannel, uint flags, uint frequency) { // Not currently implemented in ScummVM } void QMixer::qsWaveMixSetSourceVelocity(int iChannel, uint flags, const QSVECTOR &velocity) { // Not currently implemented in ScummVM } int QMixer::qsWaveMixPlayEx(int iChannel, uint flags, CWaveFile *waveFile, int loops, const QMIXPLAYPARAMS &params) { if (iChannel == -1) { // Find a free channel for (iChannel = 0; iChannel < (int)_channels.size(); ++iChannel) { if (_channels[iChannel]._sounds.empty()) break; } assert(iChannel != (int)_channels.size()); } // If the new sound replaces current ones, then clear the channel ChannelEntry &channel = _channels[iChannel]; if (flags & QMIX_CLEARQUEUE) { if (!channel._sounds.empty() && channel._sounds.front()._started) _mixer->stopHandle(channel._sounds.front()._soundHandle); channel._sounds.clear(); } // Add the sound to the channel channel._sounds.push_back(SoundEntry(waveFile, params.callback, loops, params.dwUser)); qsWaveMixPump(); return 0; } bool QMixer::qsWaveMixIsChannelDone(int iChannel) const { return _channels[iChannel]._sounds.empty(); } void QMixer::qsWaveMixPump() { // Iterate through each of the channels for (uint iChannel = 0; iChannel < _channels.size(); ++iChannel) { ChannelEntry &channel = _channels[iChannel]; // If there's a transition in sound volume in progress, handle it if (channel._volumeChangeEnd) { byte oldVolume = channel._volume; uint currentTicks = g_system->getMillis(); if (currentTicks >= channel._volumeChangeEnd) { // Reached end of transition period channel._volume = channel._volumeEnd; channel._volumeChangeStart = channel._volumeChangeEnd = 0; } else { // Transition in progress, so figure out new volume channel._volume = (int)channel._volumeStart + ((int)channel._volumeEnd - (int)channel._volumeStart) * (int)(currentTicks - channel._volumeChangeStart) / (int)channel._panRate; } debugC(DEBUG_DETAILED, kDebugCore, "qsWaveMixPump time=%u vol=%d", currentTicks, channel._volume); if (channel._volume != oldVolume && !channel._sounds.empty() && channel._sounds.front()._started) { _mixer->setChannelVolume(channel._sounds.front()._soundHandle, channel.getRawVolume()); } } // If the playing sound on the channel is finished, then call // the callback registered for it, and remove it from the list if (!channel._sounds.empty()) { SoundEntry &sound = channel._sounds.front(); if (sound._started && !_mixer->isSoundHandleActive(sound._soundHandle)) { // Sound is finished if (sound._callback) // Call the callback to signal end sound._callback(iChannel, sound._waveFile, sound._userData); // Remove sound record from channel channel._sounds.erase(channel._sounds.begin()); } } // If there's an unstarted sound at the front of a channel's // sound list, then start it playing if (!channel._sounds.empty()) { SoundEntry &sound = channel._sounds.front(); if (!sound._started) { if (channel._resetDistance) channel._distance = 0.0; // Play the wave sound._soundHandle = sound._waveFile->play( sound._loops, channel.getRawVolume()); sound._started = true; } } } } /*------------------------------------------------------------------------*/ byte QMixer::ChannelEntry::getRawVolume() const { // Emperically decided adjustment divisor for distances const double ADJUSTMENT_FACTOR = 5.0; double r = 1.0 + (_distance / ADJUSTMENT_FACTOR); double percent = 1.0 / (r * r); double newVolume = _volume * percent; return (byte)newVolume; } } // End of namespace Titanic
yinsimei/scummvm
engines/titanic/sound/qmixer.cpp
C++
gpl-2.0
8,371
""" USAGE: twitter [action] [options] ACTIONS: follow add the specified user to your follow list friends get latest tweets from your friends (default action) help print this help text that you are currently reading leave remove the specified user from your following list public get latest public tweets replies get latest replies set set your twitter status shell login the twitter shell OPTIONS: -e --email <email> your email to login to twitter -p --password <password> your twitter password -r --refresh run this command forever, polling every once in a while (default: every 5 minutes) -R --refresh-rate <rate> set the refresh rate (in seconds) -f --format <format> specify the output format for status updates -c --config <filename> read username and password from given config file (default ~/.twitter) -l --length <count> specify number of status updates shown (default: 20, max: 200) -t --timestamp show time before status lines -d --datestamp shoe date before status lines FORMATS for the --format option default one line per status verbose multiple lines per status, more verbose status info urls nothing but URLs ansi ansi colour (rainbow mode) CONFIG FILES The config file should contain a [twitter] header, and all the desired options you wish to set, like so: [twitter] email: <username> password: <password> format: <desired_default_format_for_output> prompt: <twitter_shell_prompt e.g. '[cyan]twitter[R]> '> """ import sys import time from getopt import gnu_getopt as getopt, GetoptError from getpass import getpass import re import os.path from ConfigParser import SafeConfigParser import datetime from api import Twitter, TwitterError import ansi # Please don't change this, it was provided by the fine folks at Twitter. # If you change it, it will not work. AGENT_STR = "twittercommandlinetoolpy" OPTIONS = { 'email': None, 'password': None, 'action': 'friends', 'refresh': False, 'refresh_rate': 600, 'format': 'default', 'prompt': '[cyan]twitter[R]> ', 'config_filename': os.environ.get('HOME', '') + os.sep + '.twitter', 'length': 20, 'timestamp': False, 'datestamp': False, 'extra_args': [] } def parse_args(args, options): long_opts = ['email', 'password', 'help', 'format', 'refresh', 'refresh-rate', 'config', 'length', 'timestamp', 'datestamp'] short_opts = "e:p:f:h?rR:c:l:td" opts, extra_args = getopt(args, short_opts, long_opts) for opt, arg in opts: if opt in ('-e', '--email'): options['email'] = arg elif opt in ('-p', '--password'): options['password'] = arg elif opt in ('-f', '--format'): options['format'] = arg elif opt in ('-r', '--refresh'): options['refresh'] = True elif opt in ('-R', '--refresh-rate'): options['refresh_rate'] = int(arg) elif opt in ('-l', '--length'): options["length"] = int(arg) elif opt in ('-t', '--timestamp'): options["timestamp"] = True elif opt in ('-d', '--datestamp'): options["datestamp"] = True elif opt in ('-?', '-h', '--help'): options['action'] = 'help' elif opt in ('-c', '--config'): options['config_filename'] = arg if extra_args and not ('action' in options and options['action'] == 'help'): options['action'] = extra_args[0] options['extra_args'] = extra_args[1:] def get_time_string(status, options): timestamp = options["timestamp"] datestamp = options["datestamp"] t = time.strptime(status['created_at'], "%a %b %d %H:%M:%S +0000 %Y") i_hate_timezones = time.timezone if (time.daylight): i_hate_timezones = time.altzone dt = datetime.datetime(*t[:-3]) - datetime.timedelta( seconds=i_hate_timezones) t = dt.timetuple() if timestamp and datestamp: return time.strftime("%Y-%m-%d %H:%M:%S ", t) elif timestamp: return time.strftime("%H:%M:%S ", t) elif datestamp: return time.strftime("%Y-%m-%d ", t) return "" class StatusFormatter(object): def __call__(self, status): return (u"%S%s %s" %( get_time_string(status, options), status['user']['screen_name'], status['text'])) class AnsiStatusFormatter(object): def __init__(self): self._colourMap = ansi.ColourMap() def __call__(self, status, options): colour = self._colourMap.colourFor(status['user']['screen_name']) return (u"%s%s%s%s %s" %( get_time_string(status, options), ansi.cmdColour(colour), status['user']['screen_name'], ansi.cmdReset(), status['text'])) class VerboseStatusFormatter(object): def __call__(self, status, options): return (u"-- %s (%s) on %s\n%s\n" %( status['user']['screen_name'], status['user']['location'], status['created_at'], status['text'])) class URLStatusFormatter(object): urlmatch = re.compile(r'https?://\S+') def __call__(self, status, options): urls = self.urlmatch.findall(status['text']) return u'\n'.join(urls) if urls else "" class AdminFormatter(object): def __call__(self, action, user): user_str = u"%s (%s)" %(user['screen_name'], user['name']) if action == "follow": return u"You are now following %s.\n" %(user_str) else: return u"You are no longer following %s.\n" %(user_str) class VerboseAdminFormatter(object): def __call__(self, action, user): return(u"-- %s: %s (%s): %s" % ( "Following" if action == "follow" else "Leaving", user['screen_name'], user['name'], user['url'])) status_formatters = { 'default': StatusFormatter, 'verbose': VerboseStatusFormatter, 'urls': URLStatusFormatter, 'ansi': AnsiStatusFormatter } admin_formatters = { 'default': AdminFormatter, 'verbose': VerboseAdminFormatter, 'urls': AdminFormatter, 'ansi': AdminFormatter } def get_status_formatter(options): sf = status_formatters.get(options['format']) if (not sf): raise TwitterError( "Unknown formatter '%s'" %(options['format'])) return sf() def get_admin_formatter(options): sf = admin_formatters.get(options['format']) if (not sf): raise TwitterError( "Unknown formatter '%s'" %(options['format'])) return sf() class Action(object): def ask(self, subject='perform this action', careful=False): ''' Requests fromt he user using `raw_input` if `subject` should be performed. When `careful`, the default answer is NO, otherwise YES. Returns the user answer in the form `True` or `False`. ''' sample = '(y/N)' if not careful: sample = '(Y/n)' prompt = 'You really want to %s %s? ' %(subject, sample) try: answer = raw_input(prompt).lower() if careful: return answer in ('yes', 'y') else: return answer not in ('no', 'n') except EOFError: print >>sys.stderr # Put Newline since Enter was never pressed # TODO: # Figure out why on OS X the raw_input keeps raising # EOFError and is never able to reset and get more input # Hint: Look at how IPython implements their console default = True if careful: default = False return default def __call__(self, twitter, options): action = actions.get(options['action'], NoSuchAction)() try: doAction = lambda : action(twitter, options) if (options['refresh'] and isinstance(action, StatusAction)): while True: doAction() time.sleep(options['refresh_rate']) else: doAction() except KeyboardInterrupt: print >>sys.stderr, '\n[Keyboard Interrupt]' pass class NoSuchActionError(Exception): pass class NoSuchAction(Action): def __call__(self, twitter, options): raise NoSuchActionError("No such action: %s" %(options['action'])) def printNicely(string): if sys.stdout.encoding: print string.encode(sys.stdout.encoding, 'replace') else: print string.encode('utf-8') class StatusAction(Action): def __call__(self, twitter, options): statuses = self.getStatuses(twitter, options) sf = get_status_formatter(options) for status in statuses: statusStr = sf(status, options) if statusStr.strip(): printNicely(statusStr) class AdminAction(Action): def __call__(self, twitter, options): if not (options['extra_args'] and options['extra_args'][0]): raise TwitterError("You need to specify a user (screen name)") af = get_admin_formatter(options) try: user = self.getUser(twitter, options['extra_args'][0]) except TwitterError, e: print "There was a problem following or leaving the specified user." print "You may be trying to follow a user you are already following;" print "Leaving a user you are not currently following;" print "Or the user may not exist." print "Sorry." print print e else: printNicely(af(options['action'], user)) class FriendsAction(StatusAction): def getStatuses(self, twitter, options): return reversed(twitter.statuses.friends_timeline(count=options["length"])) class PublicAction(StatusAction): def getStatuses(self, twitter, options): return reversed(twitter.statuses.public_timeline(count=options["length"])) class RepliesAction(StatusAction): def getStatuses(self, twitter, options): return reversed(twitter.statuses.replies(count=options["length"])) class FollowAction(AdminAction): def getUser(self, twitter, user): return twitter.friendships.create(id=user) class LeaveAction(AdminAction): def getUser(self, twitter, user): return twitter.friendships.destroy(id=user) class SetStatusAction(Action): def __call__(self, twitter, options): statusTxt = (u" ".join(options['extra_args']) if options['extra_args'] else unicode(raw_input("message: "))) status = (statusTxt.encode('utf8', 'replace')) twitter.statuses.update(status=status) class TwitterShell(Action): def render_prompt(self, prompt): '''Parses the `prompt` string and returns the rendered version''' prompt = prompt.strip("'").replace("\\'","'") for colour in ansi.COLOURS_NAMED: if '[%s]' %(colour) in prompt: prompt = prompt.replace( '[%s]' %(colour), ansi.cmdColourNamed(colour)) prompt = prompt.replace('[R]', ansi.cmdReset()) return prompt def __call__(self, twitter, options): prompt = self.render_prompt(options.get('prompt', 'twitter> ')) while True: options['action'] = "" try: args = raw_input(prompt).split() parse_args(args, options) if not options['action']: continue elif options['action'] == 'exit': raise SystemExit(0) elif options['action'] == 'shell': print >>sys.stderr, 'Sorry Xzibit does not work here!' continue elif options['action'] == 'help': print >>sys.stderr, '''\ntwitter> `action`\n The Shell Accepts all the command line actions along with: exit Leave the twitter shell (^D may also be used) Full CMD Line help is appended below for your convinience.''' Action()(twitter, options) options['action'] = '' except NoSuchActionError, e: print >>sys.stderr, e except KeyboardInterrupt: print >>sys.stderr, '\n[Keyboard Interrupt]' except EOFError: print >>sys.stderr leaving = self.ask(subject='Leave') if not leaving: print >>sys.stderr, 'Excellent!' else: raise SystemExit(0) class HelpAction(Action): def __call__(self, twitter, options): print __doc__ actions = { 'follow' : FollowAction, 'friends' : FriendsAction, 'help' : HelpAction, 'leave' : LeaveAction, 'public' : PublicAction, 'replies' : RepliesAction, 'set' : SetStatusAction, 'shell' : TwitterShell, } def loadConfig(filename): options = dict(OPTIONS) if os.path.exists(filename): cp = SafeConfigParser() cp.read([filename]) for option in ('email', 'password', 'format', 'prompt'): if cp.has_option('twitter', option): options[option] = cp.get('twitter', option) return options def main(args=sys.argv[1:]): arg_options = {} try: parse_args(args, arg_options) except GetoptError, e: print >> sys.stderr, "I can't do that, %s." %(e) print >> sys.stderr raise SystemExit(1) config_options = loadConfig( arg_options.get('config_filename') or OPTIONS.get('config_filename')) # Apply the various options in order, the most important applied last. # Defaults first, then what's read from config file, then command-line # arguments. options = dict(OPTIONS) for d in config_options, arg_options: for k,v in d.items(): if v: options[k] = v if options['refresh'] and options['action'] not in ( 'friends', 'public', 'replies'): print >> sys.stderr, "You can only refresh the friends, public, or replies actions." print >> sys.stderr, "Use 'twitter -h' for help." raise SystemExit(1) if options['email'] and not options['password']: options['password'] = getpass("Twitter password: ") twitter = Twitter(options['email'], options['password'], agent=AGENT_STR) try: Action()(twitter, options) except NoSuchActionError, e: print >>sys.stderr, e raise SystemExit(1) except TwitterError, e: print >> sys.stderr, e.args[0] print >> sys.stderr, "Use 'twitter -h' for help." raise SystemExit(1)
avsm/lifedb-plugins
Twitter/twitter/cmdline.py
Python
gpl-2.0
15,027
package si.virag.parkomat.modules; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.support.annotation.NonNull; import com.wdullaer.materialdatetimepicker.time.RadialPickerLayout; import com.wdullaer.materialdatetimepicker.time.TimePickerDialog; import org.threeten.bp.LocalTime; import org.threeten.bp.temporal.ChronoField; import org.threeten.bp.temporal.ChronoUnit; import rx.Observable; import rx.Subscriber; /** * Handles parking time related things */ public class TimeManager { @NonNull private final Context appContext; public TimeManager(@NonNull Context applicationContext) { this.appContext = applicationContext; } public LocalTime initialDisplayedTime() { return LocalTime.now().plus(1, ChronoUnit.HOURS); } public Observable<LocalTime> pickTime(@NonNull final Activity owner, @NonNull final LocalTime currentlySelected) { return Observable.create(new Observable.OnSubscribe<LocalTime>() { @Override public void call(final Subscriber<? super LocalTime> subscriber) { TimePickerDialog.OnTimeSetListener listener = new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute, int second) { LocalTime instant = LocalTime.now() .with(ChronoField.HOUR_OF_DAY, hourOfDay) .with(ChronoField.MINUTE_OF_HOUR, minute); subscriber.onNext(instant); } }; DialogInterface.OnDismissListener dismissListener = new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { subscriber.onCompleted(); } }; TimePickerDialog dialog = TimePickerDialog.newInstance(listener, currentlySelected.get(ChronoField.HOUR_OF_DAY), currentlySelected.get(ChronoField.MINUTE_OF_HOUR), true); dialog.setOnDismissListener(dismissListener); dialog.show(owner.getFragmentManager(), "TimePicker"); } }); } }
izacus/Parkomat
app/src/main/java/si/virag/parkomat/modules/TimeManager.java
Java
gpl-2.0
2,335
<?php if(!defined("IN_ESOTALK")) exit; /** * OpauthConnect * * @copyright Copyright © 2012 Oleksandr Golubtsov * @license GPLv2 License * @package OpauthСonnect * * This file is part of OpauthСonnect plugin. Please see the included license file for usage information */ ET::$pluginInfo["OpauthConnect"] = array( "name" => "OpauthConnect", "description" => "Sign in via social networks", "version" => "2.1", "author" => "Oleksandr Golubtsov", "authorEmail" => "alex.8fmi@gmail.com", "authorURL" => "http://alex-dev.me", "license" => "GPLv2" ); require_once "classes".DIRECTORY_SEPARATOR."OCServices.php"; require_once "classes".DIRECTORY_SEPARATOR."OpauthConnect.php"; require_once "classes".DIRECTORY_SEPARATOR."OCSettings.php"; class ETPlugin_OpauthConnect extends ETPlugin { private $settings; private $services; private $opauth_connect; public function __construct($rootDirectory) { parent::__construct($rootDirectory); ETFactory::register("ocMemberSocialModel", "OcMemberSocialModel", dirname(__FILE__)."/models/OcMemberSocialModel.class.php"); ETFactory::register("ocSettingsModel", "OcSettingsModel", dirname(__FILE__)."/models/OcSettingsModel.class.php"); $this->services = new OCServices; $this->settings = new OCSettings; } public function handler_init($sender) { if(ET::$session->get("remember") === null) ET::$session->store("remember", 1); $sender->addCSSFile($this->resource("css/opauthconnect.css")); $sender->addJSFile($this->resource("js/opauthconnect.js")); $config = array(); $config['security_salt'] = $this->settings->get(OCSettings::SECURITY_SALT); $config['path'] = URL('user/social/'); $config['callback_url'] = URL('user/social/callback/'); foreach($this->services as $service) { if($this->settings->get($service->settings->enabled)) { $config['Strategy'][$service->name] = array( $service->key => $this->settings->get($service->settings->key), $service->secret => $this->settings->get($service->settings->secret) ); foreach($service->static as $name => $value) { $config['Strategy'][$service->name][$name] = $value; } } } $this->opauth_connect = new OpauthConnect($config); } public function handler_initAdmin($sender, $menu) { $sender->addCSSFile($this->resource("css/backend.css")); $sender->addJSFile($this->resource("js/backend.js")); } public function handler_renderOpauth($sender) { $data = array( 'remember' => ET::$session->get("remember", 0), 'services' => array() ); foreach($this->services as $service) { if($this->settings->get($service->settings->enabled)) { $data['services'][$service->name] = array( 'url' => URL('user/social/'.$service->machine_name), 'icon' => URL($this->resource($service->icon)) ); } } $sender->renderView('social/oc_buttons', $data); } public function handler_settingsController_renderBefore($sender) { if(isset($sender->data['panes']) && !empty($sender->data['panes'])) { $sender->data['panes']->add('social_accounts', "<a href='".URL("settings/social/accounts")."'>".T("Social Accounts")."</a>"); } } private function login($memberId) { if($memberId) { ET::$session->loginWithMemberId($memberId); if(ET::$session->get("remember")) ET::$session->setRememberCookie($memberId); } redirect(URL()); } public function settings($sender) { $form = ETFactory::make("form"); $form->action = URL("admin/plugins/settings/OpauthConnect"); if($form->validPostBack("save") && !$form->errorCount()) { $this->settings->set(OCSettings::PASS_EMAIL_SUBJ, $form->getValue(OCSettings::PASS_EMAIL_SUBJ)); $this->settings->set(OCSettings::CONFIRM_EMAIL_SUBJ, $form->getValue(OCSettings::CONFIRM_EMAIL_SUBJ)); $this->settings->set(OCSettings::ALLOW_UNLINK, $form->getValue(OCSettings::ALLOW_UNLINK)); $this->settings->set(OCSettings::SECURITY_SALT, $form->getValue(OCSettings::SECURITY_SALT)); foreach($this->services as $service) { foreach($service->settings as $setting) { $this->settings->set($setting, $form->getValue($setting)); } } $this->settings->save(); $sender->message(T("message.changesSaved"), "success"); $sender->redirect(URL("admin/plugins")); } $form->setValue(OCSettings::SECURITY_SALT, $this->settings->get(OCSettings::SECURITY_SALT)); $form->setValue(OCSettings::ALLOW_UNLINK, $this->settings->get(OCSettings::ALLOW_UNLINK)); $form->setValue(OCSettings::CONFIRM_EMAIL_SUBJ, $this->settings->get(OCSettings::CONFIRM_EMAIL_SUBJ)); $form->setValue(OCSettings::PASS_EMAIL_SUBJ, $this->settings->get(OCSettings::PASS_EMAIL_SUBJ)); $form_services = array(); foreach($this->services as $service) { $form_services[$service->machine_name]['name'] = $service->name; $form_services[$service->machine_name]['raw_key'] = $service->key; $form_services[$service->machine_name]['raw_secret'] = $service->secret; foreach($service->settings as $k => $v) { $form_services[$service->machine_name][$k] = array( "key" => $v, "value" => $this->settings->get($v) ); } } $sender->data("form", $form); $sender->data("form_services", $form_services); return $this->view('admin/oc_settings'); } public function action_settingsController_social($sender, $action, $param1 = null) { switch($action) { case "accounts": $this->settings_social_accounts($sender); break; case "unlink": $this->settings_social_unlink_account($sender, $param1); break; default: $sender->render404(); break; } } private function settings_social_accounts($sender) { $sender->profile("social_accounts"); $accounts = ET::getInstance("ocMemberSocialModel")->getAccounts(ET::$session->userId); foreach($accounts as &$account) { $account["logo"] = URL($this->resource("images/settings/".$account["socialNetwork"].".png")); } $sender->data("accounts", $accounts); $sender->data("allow_unlink", $this->settings->get(OCSettings::ALLOW_UNLINK)); $sender->data("accounts_exist", !empty($accounts)); $sender->renderProfile($this->view("admin/oc_social_accounts")); } private function settings_social_unlink_account($sender, $id) { if(!$this->settings->get(OCSettings::ALLOW_UNLINK) || !ET::getInstance("ocMemberSocialModel")->isApropriateUser(ET::$session->userId, $id)) { $sender->render404(); return; } ET::getInstance("ocMemberSocialModel")->deleteById($id); redirect(URL("settings/social/accounts")); } public function setup($oldVersion = "") { ET::$database->structure()->table("member") ->dropColumn("fromSN") ->dropColumn("TWid") ->dropColumn("TWconfirmed") ->exec(false); ET::$database->structure()->table("oc_member_social") ->column("id", "int(11) unsigned", false) ->column("member_Id", "int(11) unsigned", false) ->column("socialNetwork", "varchar(255)", false) ->column("socialId", "varchar(255)", false) ->column("profileLink", "varchar(255)", false) ->column("name", "varchar(255)", false) ->column("confirmed", "tinyint unsigned", false) ->column("confirmationHash", "varchar(255)") ->column("confirmationSent", "int(11) unsigned", 0) ->key("id", "primary") ->key(array("socialNetwork","socialId"), "unique") ->exec(false); ET::$database->structure()->table("oc_settings") ->column("name", "varchar(50)", false) ->column("value", "varchar(100)", false) ->key("name", "primary") ->exec(false); ET::$database->query(strtr("ALTER TABLE [prefix]oc_member_social ADD FOREIGN KEY(member_Id) REFERENCES [prefix]member(memberId)", array('[prefix]' => C("esoTalk.database.prefix")))); // ET::$database->query($this->services->getSettingsSchemaQuery(C("esoTalk.database.prefix"))); return true; } private function social_auth($sender) { if(ET::$session->user) { $sender->message("You are already logged in"); redirect(URL()); } $this->opauth_connect->doRequest(); } private function social_callback($sender) { try { $response = $this->opauth_connect->getResponse(); switch($this->opauth_connect->validateAccount($response["static"]['uid'], $response["static"]['provider'])) { case OpauthConnect::ACCOUNT_CONFIRMED: $this->login($this->opauth_connect->getLastAccountValidation()); break; case OpauthConnect::ACCOUNT_NOT_EXISTS: ET::$session->store("OpauthConnect", $response["static"]); $this->social_setup($sender, $response["editable"]); return; case OpauthConnect::ACCOUNT_NOT_CONFIRMED: $sender->message("Your account was not confirmed. <a href='".URL("user/social/sendconfirmation/".$this->opauth_connect->getLastAccountValidation())."'>Send confirmation letter again</a>", "warning"); break; } } catch(Exception $ex) { $sender->message($ex->getMessage(), "warning"); } redirect(URL()); } private function social_confirm($sender, $hash) { if($result = ET::getInstance("ocMemberSocialModel")->validateConfirmationHash($hash)) { $sender->message(T("You successfully confirmed your new account"), "success"); $this->login($result); } $sender->message(T("Invalid confirmation hash"), "warning"); redirect(URL()); } private function social_remember() { ET::$session->store("remember", (int)R("remember", 0)); } private function social_sendConfirmation($sender, $row_id, $is_new_user) { $data = ET::getInstance("ocMemberSocialModel")->getConfirmationData($row_id); if(time() - $data["confirmationSent"] > OpauthConnect::CONFIRMATION_INTERVAL) { $params = array( "confirmationUrl" => URL("user/social/confirm/".$data['confirmationHash'], true), "profileLink" => $data["profileLink"], "socialName" => $data["name"], "socialNetwork" => $data["socialNetwork"], "userName" => $data["username"], "forumName" => C("esoTalk.forumTitle"), "isNewUser" => $is_new_user ); $title = strtr($this->settings->get(OCSettings::CONFIRM_EMAIL_SUBJ), array( "[forumName]" => C("esoTalk.forumTitle"), "[socialNetwork]" => $data["socialNetwork"], "[socialName]" => $data["name"], "[userName]" => $data["username"] )); sendEmail($data["email"], $title, $sender->getViewContents('emails/oc_confirmation', $params)); ET::getInstance("ocMemberSocialModel")->sentConfirmation($row_id); $sender->message("Confirmation letter was sent to your e-mail address (".$data["email"].")", "success"); } else { $sender->message(T("Confirmation letter can be sent once per 5 minutes. Please wait"), "warning"); } redirect(URL()); } private function social_setup($sender, $form_data = array()) { $session_data = ET::$session->get("OpauthConnect"); if(!$session_data) { $sender->message(T("Time is out. Please, try again"), "warning"); redirect(URL("user/login")); } $email_only = false; if(ET::memberModel()->validateEmail($session_data["email"]) == "emailTaken") { $email_only = true; } $form = ETFactory::make("form"); $form->action = URL("user/social/setup"); $sender->data("show_password", false); if($form->validPostBack("save")) { if(!$session_data["email"]) { if(!$form->getValue("email")) { $form->error("email", T("Email must be set")); } if(ET::memberModel()->validateEmail($form->getValue("email"), false) !== null) { $form->error("email", T("Email is invalid")); } } if(!$email_only) { if(!$form->getValue("generate_password")) { // @TODO: refactor this in future $sender->data("show_password", true); if(ET::memberModel()->validatePassword($form->getValue("password")) !== null) { $form->error("password", T("Password is too shot")); } elseif($form->getValue("password") != $form->getValue("password_repeat")) { $form->error("password_repeat", T("Passwords not match")); } } switch(ET::memberModel()->validateUsername($form->getValue("username"))) { case 'nameTaken': $form->error("username", T("Username is already exists")); break; case 'invalidUsername': $form->error("username", T("Username is incorrect")); break; } } if(!$form->errorCount()) { if($session_data["email"]) { $email = $session_data["email"]; $needs_confirmation = false; } else { $email = $form->getValue("email"); $needs_confirmation = true; } switch(ET::memberModel()->validateEmail($email)) { case null: $password = $form->getValue("generate_password") ? generateRandomString(12, OpauthConnect::PASSWORD_CHARS) : $form->getValue("password"); if($form->getValue("generate_password")) { $params = array( "userName" => $form->getValue("username"), "password" => $password, "forumName" => C("esoTalk.forumTitle") ); $title = strtr($this->settings->get(OCSettings::PASS_EMAIL_SUBJ), array( "[forumName]" => C("esoTalk.forumTitle"), "[userName]" => $form->getValue("username") )); sendEmail($email, $title, $sender->getViewContents('emails/oc_password', $params)); } $data = array( "username" => $form->getValue("username"), "email" => $email, "password" => $password, "account" => ACCOUNT_MEMBER, "confirmed" => true //this field is not used. just dummy value ); $memberId = ET::memberModel()->create($data); $avatar_exists = false; $is_new_user = true; break; case "emailTaken": $member = ET::memberModel()->get(array("email" => $email)); $avatar_exists = $member[0]["avatarFormat"]; $memberId = $member[0]["memberId"]; $is_new_user = null; break; } ET::$session->remove("OpauthConnect"); if(!$avatar_exists && $form->getValue("avatar")) { $avatar = ET::uploader()->saveAsImage($form->getValue("avatar"), PATH_UPLOADS."/avatars/".$memberId, C("esoTalk.avatars.width"), C("esoTalk.avatars.height"), "crop"); ET::memberModel()->updateById($memberId, array("avatarFormat" => pathinfo($avatar, PATHINFO_EXTENSION))); } $row_id = ET::getInstance("ocMemberSocialModel")->addAccount( $memberId, $session_data["provider"], $session_data["uid"], $session_data["link"], $session_data["name"], !$needs_confirmation, $needs_confirmation ? md5(uniqid(rand())) : null ); if($needs_confirmation) { $this->social_sendConfirmation($sender, $row_id, $is_new_user); } else { $this->login($memberId); } } } foreach($form_data as $key => $value) { $form->setValue($key, $value); } $sender->data("show_email", true); if($session_data["email"]) { if($form->isPostBack()) $_POST['email'] = $session_data["email"]; else $form->setValue("email", $session_data["email"]); $sender->data("show_email", false); } $sender->data("email_only", $email_only); $sender->data("form", $form); $sender->render("social/oc_account_setup"); } public function action_userController_social($sender, $action, $param1 = null, $param2 = null) { switch($action) { case "setup": $this->social_setup($sender); break; case "callback": $this->social_callback($sender); break; case "sendconfirmation": $this->social_sendConfirmation($sender, $param1, $param2); break; case "confirm": $this->social_confirm($sender, $param1); break; case "remember": $this->social_remember(); break; default: if($this->services->isServiceExists($action)) { $this->social_auth($sender); } else { $sender->render404(); } break; } } public function uninstall() {} }
phisyks/discuss
addons/plugins/OpauthConnect/plugin.php
PHP
gpl-2.0
20,268
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace Revista_Programar_Reader_Win8 { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); } } }
pikax/papreader
Revista Programar Reader Win8/MainPage.xaml.cs
C#
gpl-2.0
828
<?php /** * Element: Agents * Displays a multiselectbox of different browsers * * @package NoNumber Framework * @version 14.4.1 * * @author Peter van Westen <peter@nonumber.nl> * @link http://www.nonumber.nl * @copyright Copyright © 2014 NoNumber All Rights Reserved * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL */ defined('_JEXEC') or die; require_once JPATH_PLUGINS . '/system/nnframework/helpers/text.php'; class JFormFieldNN_Agents extends JFormField { public $type = 'Agents'; private $params = null; protected function getInput() { $this->params = $this->element->attributes(); $group = $this->get('group'); if (!is_array($this->value)) { $this->value = explode(',', $this->value); } $agents = array(); switch ($group) { /* OS */ case 'os': $agents[] = array('Windows (' . JText::_('JALL') . ')', 'Windows'); $agents[] = array('Windows 8', 'Windows nt 6.2'); $agents[] = array('Windows 7', 'Windows nt 6.1'); $agents[] = array('Windows Vista', 'Windows nt 6.0'); $agents[] = array('Windows Server 2003', 'Windows nt 5.2'); $agents[] = array('Windows XP', 'Windows nt 5.1'); $agents[] = array('Windows 2000 sp1', 'Windows nt 5.01'); $agents[] = array('Windows 2000', 'Windows nt 5.0'); $agents[] = array('Windows NT 4.0', 'Windows nt 4.0'); $agents[] = array('Windows Me', 'Win 9x 4.9'); $agents[] = array('Windows 98', 'Windows 98'); $agents[] = array('Windows 95', 'Windows 95'); $agents[] = array('Windows CE', 'Windows ce'); $agents[] = array('Mac OS (' . JText::_('JALL') . ')', '#(Mac OS|Mac_PowerPC|Macintosh)#'); $agents[] = array('Mac OSX (' . JText::_('JALL') . ')', 'Mac OS X'); $agents[] = array('Mac OSX Mountain Lion', 'Mac OS X 10.8'); $agents[] = array('Mac OSX Lion', 'Mac OS X 10.7'); $agents[] = array('Mac OSX Snow Leopard', 'Mac OS X 10.6'); $agents[] = array('Mac OSX Leopard', 'Mac OS X 10.5'); $agents[] = array('Mac OSX Tiger', 'Mac OS X 10.4'); $agents[] = array('Mac OSX Panther', 'Mac OS X 10.3'); $agents[] = array('Mac OSX Jaguar', 'Mac OS X 10.2'); $agents[] = array('Mac OSX Puma', 'Mac OS X 10.1'); $agents[] = array('Mac OSX Cheetah', 'Mac OS X 10.0'); $agents[] = array('Mac OS (classic)', '#(Mac_PowerPC|Macintosh)#'); $agents[] = array('Linux', '#(Linux|X11)#'); $agents[] = array('Open BSD', 'OpenBSD'); $agents[] = array('Sun OS', 'SunOS'); $agents[] = array('QNX', 'QNX'); $agents[] = array('BeOS', 'BeOS'); $agents[] = array('OS/2', 'OS/2'); break; /* Browsers */ case 'browsers': $agents[] = array('Chrome (' . JText::_('JALL') . ')', 'Chrome'); $agents[] = array('Chrome 35', 'Chrome/35.'); $agents[] = array('Chrome 34', 'Chrome/34.'); $agents[] = array('Chrome 33', 'Chrome/33.'); $agents[] = array('Chrome 32', 'Chrome/32.'); $agents[] = array('Chrome 31', 'Chrome/31.'); $agents[] = array('Chrome 30', 'Chrome/30.'); $agents[] = array('Chrome 29', 'Chrome/29.'); $agents[] = array('Chrome 28', 'Chrome/28.'); $agents[] = array('Chrome 27', 'Chrome/27.'); $agents[] = array('Chrome 26', 'Chrome/26.'); $agents[] = array('Chrome 25', 'Chrome/25.'); $agents[] = array('Chrome 24', 'Chrome/24.'); $agents[] = array('Chrome 23', 'Chrome/23.'); $agents[] = array('Chrome 22', 'Chrome/22.'); $agents[] = array('Chrome 21', 'Chrome/21.'); //$agents[] = array('Chrome 31-40', '#Chrome/(3[1-9]|40)\.#'); //$agents[] = array('Chrome 21-30', '#Chrome/(2[1-9]|30)\.#'); $agents[] = array('Chrome 11-20', '#Chrome/(1[1-9]|20)\.#'); $agents[] = array('Chrome 1-10', '#Chrome/([1-9]|10)\.#'); $agents[] = array('Firefox (' . JText::_('JALL') . ')', 'Firefox'); $agents[] = array('Firefox 30', 'Firefox/30.'); $agents[] = array('Firefox 29', 'Firefox/29.'); $agents[] = array('Firefox 28', 'Firefox/28.'); $agents[] = array('Firefox 27', 'Firefox/27.'); $agents[] = array('Firefox 26', 'Firefox/26.'); $agents[] = array('Firefox 25', 'Firefox/25.'); $agents[] = array('Firefox 24', 'Firefox/24.'); $agents[] = array('Firefox 23', 'Firefox/23.'); $agents[] = array('Firefox 22', 'Firefox/22.'); $agents[] = array('Firefox 21', 'Firefox/21.'); //$agents[] = array('Firefox 21-30', '#Firefox/(2[1-9]|30)\.#'); $agents[] = array('Firefox 11-20', '#Firefox/(1[1-9]|20)\.#'); $agents[] = array('Firefox 1-10', '#Firefox/([1-9]|10)\.#'); $agents[] = array('Internet Explorer (' . JText::_('JALL') . ')', 'MSIE'); $agents[] = array('Internet Explorer 10.6', 'MSIE 10.6'); $agents[] = array('Internet Explorer 10.0', 'MSIE 10.0'); $agents[] = array('Internet Explorer 10', 'MSIE 10.'); $agents[] = array('Internet Explorer 9', 'MSIE 9.'); $agents[] = array('Internet Explorer 8', 'MSIE 8.'); $agents[] = array('Internet Explorer 7', 'MSIE 7.'); $agents[] = array('Internet Explorer 1-6', '#MSIE [1-6]\.#'); $agents[] = array('Opera (' . JText::_('JALL') . ')', 'Opera'); $agents[] = array('Opera 13', 'Opera/13.'); $agents[] = array('Opera 12', 'Opera/12.'); $agents[] = array('Opera 11', 'Opera/11.'); $agents[] = array('Opera 10', 'Opera/10.'); $agents[] = array('Opera 1-9', '#Opera/[1-9]\.#'); $agents[] = array('Safari (' . JText::_('JALL') . ')', 'Safari'); $agents[] = array('Safari 8', '#Version/8\..*Safari/#'); $agents[] = array('Safari 7', '#Version/7\..*Safari/#'); $agents[] = array('Safari 6', '#Version/6\..*Safari/#'); $agents[] = array('Safari 5', '#Version/5\..*Safari/#'); $agents[] = array('Safari 4', '#Version/4\..*Safari/#'); $agents[] = array('Safari 1-3', '#Version/[1-3]\..*Safari/#'); break; /* Mobile browsers */ case 'mobile': $agents[] = array(JText::_('JALL'), 'mobile'); $agents[] = array('Android', 'Android'); $agents[] = array('Blackberry', 'Blackberry'); $agents[] = array('IE Mobile', 'IEMobile'); $agents[] = array('iPad', 'iPad'); $agents[] = array('iPhone', 'iPhone'); $agents[] = array('iPod Touch', 'iPod'); $agents[] = array('NetFront', 'NetFront'); $agents[] = array('Nokia', 'NokiaBrowser'); $agents[] = array('Opera Mini', 'Opera Mini'); $agents[] = array('Opera Mobile', 'Opera Mobi'); $agents[] = array('UC Browser', 'UC Browser'); break; } $options = array(); foreach ($agents as $agent) { $option = JHtml::_('select.option', $agent['1'], $agent['0']); $options[] = $option; } $attr = ''; $attr .= $this->get('size') ? ' size="' . (int) $this->get('size') . '"' : ''; $attr .= ' multiple="multiple"'; return JHtml::_('select.genericlist', $options, $this->name, trim($attr), 'value', 'text', $this->value, $this->id); } private function get($val, $default = '') { return (isset($this->params[$val]) && (string) $this->params[$val] != '') ? (string) $this->params[$val] : $default; } }
L16jovenesTIC/portal-web
plugins/system/nnframework/fields/agents.php
PHP
gpl-2.0
7,025
/* Interpréteur GOTO++ Copyright 2002 Sidoine de Wispelaere Ce programme est un logiciel libre ; vous pouvez le redistribuer et/ou le modifier sous les termes de la GNU General Public Licence telle que publiée par la Free Software Fundation ; soit dans la version 2 de la Licence, soit (à votre choix) dans une version ultérieure. Ce programme est distribué dans l'espoir qu'il sera utile mais SANS AUCUNE GARANTIE ; sans même la garantie implicite qu'il soit COMMERCIALISABLE ou ADEQUAT POUR UN USAGE PARTICULIER. Voir la GNU General Public Licence pour plus de détails. Vous devriez avoir reçu une copie de la GNU General Public Licence avec ce programme ; dans le cas contraire, écrivez à : Free Software Fundation, Inc. 59 Temple Place - Suite 330, Boston, MA 02111-1307, US **** Voici le fameux compilateur, qui vous domine du haut de ses je ne sais combien de lignes. Bon courage pour comprendre tout ça. */ #include <gotopp/base.h> #include <gotopp/icompilateur.h> #include <gotopp/erreur.h> #include "compriv.h" #include <gotopp/global.h> using namespace GotoPP; using namespace std; namespace GotoPP { bool ALPHA(carac c) { return ((c>='A' && c<='Z')||(c>='a' && c<='z')); } bool ALPHANUM(carac c) { return ((c>='A' && c<='Z')||(c>='a' && c<='z')||(c>='0' && c<='9')); } inline bool EGAL(const carac * x, const carac * y, size_t ly) { return (czlen(x)==ly && memcmp(x,y,ly*sizeof(carac))==0); } // #define EGALMC(_T(y) ((lClef==sizeof(_T(y))/sizeof(carac)-1)&&(memcmp(MotClef,_T(y),sizeof(_T(y))-sizeof(carac))==0)) const int PRI_CONSTANTE=1; const int PRI_TAILLE=2; const int PRI_PLUSMOINS=5; const int PRI_FOIS=8; const int PRI_MODULO=8; const int PRI_CONCAT=9; const int PRI_EXEC=10; const int PRI_DEF=15; const int PRI_REGOTO=18; const int PRI_ABSOLUE=3; const int PRI_OPPOSE=3; const int PRI_TYPEDE=1; const int PRI_VIRGULE=999; const int PRI_MAX=1000; const int PRI_COLLE=1001; const int PRI_PAR_O=0; const int PRI_PAR_F=1003; const int PRI_FIN=1004; const int PRI_NOUVEAU=10; const int PRI_COMP=14; const int PRI_NON=4; const int PRI_OU=16; const int PRI_ET=17; const int PRI_SWITCH=20; const int PRI_OUBIN=12; const int PRI_ETBIN=13; const int PRI_DECALAGEBIN=7; index_t LireEtiquette(bool & local); carac prochainFichier[512]; } /* Le principe de base du compilateur est expliqué dans CompilerSeparateur. * Explication sur les variables "longues", c'est à dire les variables dotées de propriétés, d'indices de tableau, etc. machin.chose[truc+13][chose].bidule= Si une variable est terminée par . ou [ alors cette variable est une variable longue. Une variable longue est entourée de parenthèses dont la priorité est celle d'une constante (<> des vraies parenthèses). variables longues => flag variablelongue=true on saute le point par la suite : soit on lit [ soit on lit des mots clefs => tout le reste génère une erreur Lecture de [ : variablelongue=false Lecture de ] : variablelongue=true en lisant une variable si le flag variablelongue=true c'est une propriété si après un ] ou une variable il n'y a pas . ou [ alors on dépile les variables longues en mettant la parenthèse finale et variablelongue=false */ //namespace GotoPP { // namespace Compilateur { inline void Compilateur::AjParO(uint priorite=PRI_PAR_O) { Instr[nInstr].p=priorite; Instr[nInstr].pVal=nValeurs; Instr[nInstr].nVal=0; Instr[nInstr++].Special=SPE_PAR_O; } inline void Compilateur::AjParF() { Instr[nInstr].p=PRI_PAR_F; Instr[nInstr].pVal=nValeurs; Instr[nInstr].nVal=0; Instr[nInstr++].Special=SPE_PAR_F; } inline void Compilateur::AjDebutParams() { Instr[nInstr].p=PRI_CONSTANTE; Instr[nInstr].pVal=nValeurs; Instr[nInstr].nVal=0; Instr[nInstr].Code= Code::I_DEBUTPARAM; Instr[nInstr++].Special=SPE_NORMAL; } inline void Compilateur::AjCode(Code code, uint Priorite=PRI_CONSTANTE) { Instr[nInstr].p=Priorite; Instr[nInstr].pVal=nValeurs; Instr[nInstr].nVal=0; Instr[nInstr].Code = code; Instr[nInstr++].Special=SPE_NORMAL; } inline void Compilateur::AjNoOp(uint priorite) { Instr[nInstr].p=priorite; Instr[nInstr].pVal=nValeurs; Instr[nInstr].nVal=0; Instr[nInstr++].Special=SPE_NOOP; } inline void Compilateur::AjExpReg(carac *er, carac *modif) { Instr[nInstr-1].nVal++; Valeur[nValeurs].Type=TYPE_OBJETC; Valeur[nValeurs++].v.o=regexp::Creer(er, modif); } inline void Compilateur::AjEntier(int e) { Instr[nInstr-1].nVal++; Valeur[nValeurs].Type=TYPE_ENTIER; Valeur[nValeurs++].v.i=e; } inline void Compilateur::AjType(type t) { Instr[nInstr-1].nVal++; Valeur[nValeurs].Type=TYPE_TYPE; Valeur[nValeurs++].v.i=t; } inline void Compilateur::AjCarac(carac c) { Instr[nInstr-1].nVal++; Valeur[nValeurs].Type=TYPE_CARAC; Valeur[nValeurs++].v.i=c; } inline void Compilateur::AjChances(float f) { Instr[nInstr-1].nVal++; Valeur[nValeurs].Type=TYPE_CHANCES; Valeur[nValeurs++].v.f=f; } inline void Compilateur::AjChaine(carac *c,size_t l) { Instr[nInstr-1].nVal++; Valeur[nValeurs].Type=TYPE_CHAINE; Valeur[nValeurs++].v.c=chaineval::CreerFormat(c,l); } inline void Compilateur::AjEntierType(int e,type Type) { Instr[nInstr-1].nVal++; Valeur[nValeurs].Type=Type; Valeur[nValeurs++].v.i=e; } inline void Compilateur::AjPtrType(Symbole * ptr, type Type) { Instr[nInstr-1].nVal++; Valeur[nValeurs].Type=Type; Valeur[nValeurs++].v.ptr=ptr; } inline bool Compilateur::EstNouveauSymbole(Symbole * s) { return s == nullptr; } void Compilateur::SupprimerVarLongue() { nInstr=VarLongue[iVarLongue].nInstrsDepart; nValeurs=Instr[nInstr].pVal; } bool Compilateur::CompilerOperateur() { if (*Source=='@' && Source[1]=='%' && Source[2]=='N' && Source[3]=='e') { clog << TXT("Bien tenté mais ça ne marche pas.\n"); Source+=4; } else if (*Source=='@' && (Source[1]=='+'||Source[1]=='-'||Source[1]==':')) { Source++; if (*Source=='+') AjCode(Code::I_EMPILER2); else if (*Source=='-') AjCode(Code::I_DEPILER2); else if (*Source==':') AjCode(Code::I_VALEUR2); Source++; } else if (*Source==SEP_PROP) //Sépare les propriétés { if (VarLongue[iVarLongue].Type.l==0) throw TXT("@ doit être placé après un nom de variable"); Source++; SauterEspaces(); ChercherMotClef(); if (lClef==0) throw TXT("@ doit être suivi d'un nom de pingouin"); Symbole * prop=ChercherSymboleDans(VarLongue[iVarLongue].Type.Dernier()); CompilerVariable(prop,VarLongue[iVarLongue].Val); } else if (*Source=='|') { Source++; if (*Source=='*') AjCode(Code::I_ETBIN,PRI_ETBIN); else if (*Source=='+') AjCode(Code::I_OUBIN,PRI_OUBIN); else if (*Source=='<') AjCode(Code::I_DECALG,PRI_DECALAGEBIN); else if (*Source=='>') AjCode(Code::I_DECALD,PRI_DECALAGEBIN); else throw TXT("opérateur binaire inconnu"); Source++; } else if (*Source=='?' && nInstr==0) { if (AcSwitch.l==0) throw TXT("on n'est pas dans un GOTOMULTIPLE"); Source++; if (czncmp(Source,_T("défaut?"),7)==0) { Source+=7; programme->Switch[AcSwitch.Dernier()]->PosDefaut=(code*)Ins.t; } else LigneAc=LP_CAS; } else if (*Source=='!') { Source++; if (*Source>='0' && *Source<='9') { ProbaSauterLigne=0; do { ProbaSauterLigne*=10; ProbaSauterLigne+=*Source-'0'; Source++; } while (*Source>='0' && *Source<='9'); } else ProbaSauterLigne=90; InstrAc=IP_OPERATEUR; } else if (*Source=='`') { Source++; AjCode(Code::I_TYPEDE,PRI_TYPEDE); } else if (*Source=='_') { Source++; AjCode(Code::I_CONCAT,PRI_CONCAT); InstrAc=IP_OPERATEUR; } else if (*Source=='"') { AjCode(Code::I_VALEURCLEF); Source++; InstrAc=IP_OPERATEUR; } else if (*Source=='#') { AjCode(Code::I_VALEUR); Source++; InstrAc=IP_OPERATEUR; } else if (*Source=='}') { AjParO(PRI_CONSTANTE); Source++; InstrAc=IP_PARO; } else if ((*Source=='{')||(*Source==')')) { AjParF(); Source++; } else if (*Source=='~') { Source++; if (*Source=='~') { AjCode(Code::I_NONOPPOSE,PRI_OPPOSE); Source++; } else AjCode(Code::I_OPPOSE,PRI_OPPOSE); InstrAc=IP_OPERATEUR; } else if (*Source=='=') { Source++; if (*Source=='-') { Source++; AjCode(Code::I_DECREMENTER,PRI_DEF); } else if (*Source=='+') { Source++; AjCode(Code::I_INCREMENTER,PRI_DEF); } else if (*Source=='=') { Source++; AjCode(Code::I_INSTANCEDE,PRI_DEF); } else AjCode(Code::I_DEFINIR,PRI_DEF); InstrAc=IP_OPERATEUR; } else if (*Source==':') { Source++; if (*Source=='=') { AjCode(Code::I_DIVISEREGAL,PRI_DEF); Source++; } else AjCode(Code::I_DIVISE,PRI_FOIS); InstrAc=IP_OPERATEUR; } else if ((*Source=='*')&&(Source[1]=='=')) { Source+=2; AjCode(Code::I_MULTIPLIEREGAL,PRI_DEF); InstrAc=IP_OPERATEUR; } else if (*Source=='+') { Source++; if (*Source=='+') { Source++; AjCode(Code::I_SUPERPLUS,PRI_PLUSMOINS); } else { AjCode(Code::I_AJOUTER,PRI_PLUSMOINS); //AjOperateurVV(OPVV_PLUS); } InstrAc=IP_OPERATEUR; } else if (*Source=='-') { AjCode(Code::I_SOUSTRAIRE,PRI_PLUSMOINS); Source++; InstrAc=IP_OPERATEUR; } else if (*Source=='(') { Source++; AjCode(Code::I_EXECVAL,PRI_EXEC); //On ferme la parenthèse qui *doit* avoir été ouverte //avant de mettre la valeur dans la pile AjParF(); AjParO(); AjDebutParams(); } else if (*Source=='%') { if (NiveauGourou>2) throw TXT("le % est interdit pour les gourous de niveau supérieur à 2"); bool local; Symbole * s=LireEtiquette(local); if (!EstNouveauSymbole(s) && s->EstClasse()) CompilerClasse(s); else CompilerVariable(s, false); } else return false; return true; } void Compilateur::DebutBloc(TypeBloc Type, Symbole * espace) { Bloc * bloc=new Bloc(); bloc->type=Type; bloc->depart=(int)Ins.t; if (espace==0) { Symbole * parent; if (blocs.l>0) parent=blocs.Dernier()->symbole; else parent=programme->symboleGlobal; //On crée un symbole vide espace=new Symbole(_T(""),parent,Symbole::Bloc); if (parent->PeutContenirLocaux()) espace->taille=parent->taille; programme->symbole.Etendre(espace); } bloc->symbole=espace; blocs.Etendre(bloc); LigneAc=LP_DEBUTBLOC; } void Compilateur::FinBloc() { if (blocs.l==0) throw TXT("pas de bloc ouvert"); bool Sinon=false; switch(blocs.Dernier()->type) { case TypeBloc::Rien: break; case TypeBloc::Sinon: //clog << "bloc sinon terminé en ligne "<<Ligne<<'\n'; if (RefEtiqA.l==0) throw TXT("un AC sans AUTOGOTOZ"); Ins.ChgGotoRel(RefEtiqA.Dernier().Etiq,(int)Ins.t); RefEtiqA.l--; break; case TypeBloc::Si: { //clog << "bloc si terminé en ligne "<<Ligne<<'\n'; //On regarde si il y a un sinon après carac *src=Source; int ligne=Ligne; do { SauterEspaces(); if (*Source=='\n') { Ligne++; Source++; } else if (*Source=='/') Source++; else break; } while (1); if (Source[0]=='A' && Source[1]=='C' && Source[2]=='A' && Source[3]=='C' && (ucarac(Source[4])<=' '||Source[4]=='/')) { Source+=4; SauterEspaces(); if ((nInstr)||(*Source!='\n' && *Source!=0 && *Source!='/')) throw TXT("ACAC doit être seul sur la ligne"); //L'équivalent de sinon : insère un GOTO vers la suite //puis un AC SauterEspaces(); Ins.AjouterCode(Code::I_GOTOR); //Cible d'un AUTOGOTOZ qui crée un GOTOPASMALIN int cible=RefEtiqA.Dernier().Etiq; RefEtiqA.Dernier().Etiq=(int)Ins.t; Ins.AjouterEntier(0); Ins.ChgGotoRel(cible,(int)Ins.t); Sinon=true; } else { Source=src; Ligne=ligne; if (RefEtiqA.l==0) throw TXT("un AC sans AUTOGOTOZ"); Ins.ChgGotoRel(RefEtiqA.Dernier().Etiq,(int)Ins.t); RefEtiqA.l--; } break; } case TypeBloc::ForEach: { int Depart=(int)Ins.t; Ins.AjouterCode(Code::I_VARIABLELOC); Ins.AjouterEntier(blocs.Dernier()->indice->indice); Ins.AjouterCode(Code::I_ENTIER); Ins.AjouterEntier(1); Ins.AjouterCode(Code::I_INCREMENTER); Ins.AjouterCode(Code::I_GOTOR); Ins.AjouterGotoRel(blocs.Dernier()->depart); for (index_t e=0; e<blocs.Dernier()->continues.l;e++) Ins.ChgGotoRel(blocs.Dernier()->continues[e],Depart); for (index_t e=0; e<blocs.Dernier()->breaks.l;e++) Ins.ChgGotoRel(blocs.Dernier()->breaks[e],(int)Ins.t); break; } case TypeBloc::For: { int Depart=(int)Ins.t; if (blocs.Dernier()->pasDuFor) { LigneDeCode * ldc=blocs.Dernier()->pasDuFor; CreerCodeFinal(*ldc); delete ldc; } Ins.AjouterCode(Code::I_GOTOR); Ins.AjouterGotoRel(blocs.Dernier()->depart); for (index_t e=0; e<blocs.Dernier()->continues.l;e++) Ins.ChgGotoRel(blocs.Dernier()->continues[e],Depart); for (index_t e=0; e<blocs.Dernier()->breaks.l;e++) Ins.ChgGotoRel(blocs.Dernier()->breaks[e],(int)Ins.t); break; } case TypeBloc::TantQue: { //clog << "bloc tantque terminé en ligne "<<Ligne<<'\n'; Ins.AjouterCode(Code::I_GOTOR); Ins.AjouterGotoRel(blocs.Dernier()->depart); for (index_t e=0; e<blocs.Dernier()->continues.l;e++) Ins.ChgGotoRel(blocs.Dernier()->continues[e],blocs.Dernier()->depart); for (index_t e=0; e<blocs.Dernier()->breaks.l;e++) Ins.ChgGotoRel(blocs.Dernier()->breaks[e],(int)Ins.t); break; } case TypeBloc::Switch: { //clog << "bloc switch terminé en ligne "<<Ligne<<'\n'; if (AcSwitch.l==0) throw TXT("une fin de GOTOMULTIPLE sans GOTOMULTIPLE ouvert"); if (programme->Switch[AcSwitch.Dernier()]->PosDefaut== nullptr) programme->Switch[AcSwitch.Dernier()]->PosDefaut=reinterpret_cast<code*>(Ins.t); //Trions les switchs qsort(programme->Switch[AcSwitch.Dernier()]->Cas.t, programme->Switch[AcSwitch.Dernier()]->Cas.l,sizeof(CCasSwitch), CompCasSwitch); AcSwitch.l--; for (index_t e=0; e<blocs.Dernier()->breaks.l;e++) Ins.ChgGotoRel(blocs.Dernier()->breaks[e],static_cast<int>(Ins.t)); break; } case TypeBloc::Fonction: //clog << "bloc fonction terminé en ligne "<<Ligne<<'\n'; AjCode(Code::I_RETOUR,PRI_EXEC); break; case TypeBloc::Classe: break; #ifdef _DEBUG default: throw TXT("bloc de type inconnu"); #endif } blocs.EffacerDernier(); if (blocs.l==0) { /*//On fait le lien des étiquettes locales qsort(&LabelL.Premier(),LabelL.l,sizeof(SLabel),CmpLabels); //clog << RefEtiq.l << " références à des étiquettes \n"; for (index_t z=0; z<RefEtiqL.l; z++) { int *k=(int*)&Ins.c[RefEtiqL[z]]; int v=*k; SLabelL * l=(SLabelL*)bsearch(&v,&LabelL.Premier(),LabelL.l,sizeof(SLabelL),CmpLabels); if (!l) throw TXT("il est fait référence à une étiquette locale qui n'existe pas dans ce bloc, à toi de trouver laquelle"); *k=l->Valeur-RefEtiqL[z]-sizeof(int); } LabelL.l=0; RefEtiqL.l=0;*/ } if (blocs.Dernier()->classeSpecifiee) blocs.EffacerDernier(); if (Sinon) DebutBloc(TypeBloc::Sinon); } bool Compilateur::CompilerMotClef0() { if (EstMotClef(_T("bush")) || EstMotClef(_T("deubeulyou"))) { SauterEspaces(); ChercherMotClef(); if (lClef==0) throw TXT("une constante doit avoir un nom"); Symbole * symb=programme->NouvelleConstante(MotClef,lClef); SauterEspaces(); if (*Source!='=') throw TXT("il manque le = après le nom de la constante"); Source++; AjCode(Code::I_CONSTVAR,PRI_DEF); AjPtrType(symb,TYPE_SYMBOLE); } else if (EstMotClef(_T("BLOC"))) { DebutBloc(TypeBloc::Rien); } else if (EstMotClef(_T("FINBLOC"))) { FinBloc(); } else if (EstMotClef(_T("FINGOTOMULTIPLE"))) { if (blocs.l==0 || blocs.Dernier()->type!= TypeBloc::Switch) throw TXT("FINGOTOMULTIPLE doit fermer un GOTOMULTIPLE"); FinBloc(); } else if (EstMotClef(_T("GOTOMULTIPLE"))) { AjCode(Code::I_SWITCH,PRI_SWITCH); AjEntier((int)programme->Switch.l); AcSwitch.Etendre((int)programme->Switch.l); CSwitch * swit=new CSwitch(); programme->Switch.Etendre(swit); CibleAuto++;//Pour les "arret" DebutBloc(TypeBloc::Switch); } else if (EstMotClef(_T("et"))) { AjCode(Code::I_ET,PRI_ET); AjEntier((int)EtOu.l); AjCode(Code::I_FINOUET,PRI_ET); AjEntier((int)EtOu.l); EtOu.Etendre(-1); } else if (EstMotClef(_T("ou"))) { AjCode(Code::I_OU,PRI_OU); AjEntier((int)EtOu.l); AjCode(Code::I_FINOUET,PRI_OU); AjEntier((int)EtOu.l); EtOu.Etendre(-1); } else if (EstMotClef(_T("eg"))) { AjCode(Code::I_EGAL,PRI_COMP); } else if (EstMotClef(_T("diff"))) { AjCode(Code::I_DIFFERENT,PRI_COMP); } else if (EstMotClef(_T("inf"))) { AjCode(Code::I_INFERIEUR,PRI_COMP); } else if (EstMotClef(_T("sup"))) { AjCode(Code::I_SUPERIEUR,PRI_COMP); } else if (EstMotClef(_T("supeg"))) { AjCode(Code::I_SUPEGAL,PRI_COMP); } else if (EstMotClef(_T("infeg"))) { AjCode(Code::I_INFEGAL,PRI_COMP); } else if (EstMotClef(_T("non"))) { AjCode(Code::I_NON,PRI_NON); } else if (EstMotClef(_T("AUTOGOTOZ"))) { AjCode(Code::I_GOTOZEROR,PRI_EXEC); AjEntierType(0,TYPE_ETIQAUTO); DebutBloc(TypeBloc::Si); } else if (EstMotClef(_T("TantQue"))) { DebutBloc(TypeBloc::TantQue); AjCode(Code::I_GOTOZEROR,PRI_EXEC); AjEntierType((int)blocs.l-1,TYPE_ETIQAUTOBREAK); } else if (EstMotClef(_T("costaud"))) { DebutBloc(TypeBloc::For); LigneAc=LP_FOR_INIT; } else if (EstMotClef(_T("PouCharque"))) { SauterEspaces(); Symbole * classe=ChercherSymbole(); if (EstNouveauSymbole(classe) || !classe->EstClasse()) throw TXT("classe de la variable de parcours indéfinie"); SauterEspaces(); ChercherMotClef(); if (lClef==0) throw TXT("indiquez un nom pour la variable de parcours"); DebutBloc(TypeBloc::ForEach); Symbole * s=blocs.Dernier()->symbole; //On crée les trois variables locales utilisées blocs.Dernier()->indice=programme->NouveauSymbole(_T("indice"),6,CType(symboleEntier),s); DernierSymbole().type=Symbole::VariableLocale; DernierSymbole().indice=(index_t)s->taille++; blocs.Dernier()->tableau=programme->NouveauSymbole(_T("tableau"),7,CType(classe),s); DernierSymbole().TypeAc.Empiler(symboleTableau); DernierSymbole().type=Symbole::VariableLocale; DernierSymbole().indice=(index_t)s->taille++; blocs.Dernier()->iterateur=programme->NouveauSymbole(MotClef,lClef,CType(classe),s); DernierSymbole().type=Symbole::VariableLocale; DernierSymbole().indice=(index_t)s->taille++; index_t svarLoc=(index_t)(blocs[blocs.l-2]->symbole->taille); AjCode(Code::I_VARIABLELOC,PRI_CONSTANTE); AjPtrType(blocs.Dernier()->indice,TYPE_VARIABLE); AjCode(Code::I_ENTIER,PRI_CONSTANTE); AjEntier(0); AjCode(Code::I_DEFINIR,PRI_CONSTANTE); AjCode(Code::I_VARIABLELOC,PRI_CONSTANTE); AjPtrType(blocs.Dernier()->tableau,TYPE_VARIABLE); AjCode(Code::I_INSTANCEDE,PRI_MAX); LigneAc=LP_FOREACH_INIT; } else if (EstMotClef(_T("arret"))) { AjCode(Code::I_GOTOR,PRI_EXEC); int Cible=int(blocs.l)-1; while (Cible>=0 && blocs[Cible]->type!= TypeBloc::Fonction && blocs[Cible]->type!= TypeBloc::TantQue && blocs[Cible]->type!= TypeBloc::Switch && blocs[Cible]->type!= TypeBloc::For && blocs[Cible]->type!= TypeBloc::ForEach) Cible--; if (blocs[Cible]->type== TypeBloc::Fonction) throw TXT("interdit de sortir d'une fonction avec arret"); if (Cible<0) throw TXT("un arret doit se trouver dans un bloc"); AjEntierType(Cible,TYPE_ETIQAUTOBREAK); } else if (EstMotClef(_T("continue"))) { AjCode(Code::I_GOTOR,PRI_EXEC); int Cible=int(blocs.l)-1; while (Cible>=0 && blocs[Cible]->type!= TypeBloc::Fonction && blocs[Cible]->type!= TypeBloc::TantQue && blocs[Cible]->type!= TypeBloc::For && blocs[Cible]->type!= TypeBloc::ForEach) Cible--; if (blocs[Cible]->type== TypeBloc::Fonction) throw TXT("interdit de sortir d'une fonction avec continue"); if (Cible<0) throw TXT("un continue doit se trouver dans un TantQue"); AjEntierType(Cible,TYPE_ETIQAUTOCONTINUE); } else if (EstMotClef(_T("AC"))) { if (nInstr) throw TXT("AC doit être en début de ligne"); if ((blocs.l==0 || (blocs.Dernier()->type != TypeBloc::Si&&blocs.Dernier()->type != TypeBloc::Sinon))) throw TXT("un AC doit terminer un AUTOGOTOZ"); FinBloc(); } else if (EstMotClef(_T("faiblard"))) { SauterEspaces(); if ((nInstr)||(*Source!='\n' && *Source!=0)) throw TXT("faiblard doit être seul sur la ligne"); if (blocs.l==0 || blocs.Dernier()->type!= TypeBloc::For) throw TXT("un faiblard doit terminer un costaud"); FinBloc(); } else if (EstMotClef(_T("FinTantQue"))) { SauterEspaces(); if ((nInstr)||(*Source!='\n' && *Source!=0)) throw TXT("FinTantQue doit être seul sur la ligne"); if (blocs.l==0 || (blocs.Dernier()->type!= TypeBloc::TantQue && blocs.Dernier()->type!= TypeBloc::ForEach)) throw TXT("un FinTantQue doit terminer un TantQue ou un PouCharque"); FinBloc(); } else if (EstMotClef(_T("ACAC"))) { throw TXT("que fait ce ACAC ici ?"); } else return false; return true; } bool Compilateur::CompilerMotClef1() { if (EstMotClef(_T("GOTOPASMALIN"))) { SauterEspaces(); bool locale; Symbole * c=LireEtiquette(locale); if (locale) { AjCode(Code::I_GOTOR,PRI_CONSTANTE); AjPtrType(c,TYPE_ETIQLOC); } else { AjCode(Code::I_GOTO,PRI_CONSTANTE); AjPtrType(c,TYPE_ETIQUETTE); } } else if (EstMotClef(_T("GOTONULPOURLESNULS"))) { SauterEspaces(); bool Locale; Symbole * c=LireEtiquette(Locale); if (Locale) { AjCode(Code::I_GOTOZEROR,PRI_EXEC); AjPtrType(c,TYPE_ETIQLOC); } else { AjCode(Code::I_GOTOZERO,PRI_EXEC); AjPtrType(c,TYPE_ETIQUETTE); } } else if (EstMotClef(_T("GOTONONNULPOURLESNULS"))) { SauterEspaces(); bool Locale; Symbole * c=LireEtiquette(Locale); if (Locale) { AjCode(Code::I_GOTONONZEROR,PRI_EXEC); AjPtrType(c,TYPE_ETIQLOC); } else { AjCode(Code::I_GOTONONZERO,PRI_EXEC); AjPtrType(c,TYPE_ETIQUETTE); } } else return false; return true; } bool Compilateur::SymboleDisponible() { Symbole * verifie=ChercherSymboleSimple(); if (!EstNouveauSymbole(verifie) && verifie->parent==blocs.Dernier()->symbole) return false; return true; } bool Compilateur::CompilerMotClef2() { if (EstMotClef(_T("estrefvalide"))) { AjCode(Code::I_ESTREFVALIDE,PRI_CONSTANTE); } else if (EstMotClef(_T("RESTEDELADIVISIONPAR"))) { AjCode(Code::I_MODULO,PRI_MODULO); } else if (EstMotClef(_T("monpitipingouin"))) { AjCode(Code::I_THIS,PRI_CONSTANTE); } else if (EstMotClef(_T("encasderreurGOTO"))) { SauterEspaces(); bool Locale; Symbole * c=LireEtiquette(Locale); if (Locale) { AjCode(Code::I_ENERREURR,PRI_CONSTANTE); AjPtrType(c,TYPE_ETIQLOC); } else { AjCode(Code::I_ENERREUR,PRI_CONSTANTE); AjPtrType(c,TYPE_ETIQUETTE); } } else if (EstMotClef(_T("GOTOBIBLIOTHEQUE"))) { SauterEspaces(); ChercherMotClef(); if (lClef==0) throw TXT("le nom de la bibliothèque de fonctions n'est pas indiqué"); for (index_t b=0; b<programme->fichierSource.l; b++) if (EGAL(programme->fichierSource[b]->Nom,MotClef,lClef)) return true; FichierSource * fichierSource=new FichierSource(); programme->fichierSource.Etendre(fichierSource); if (!fichierSource->Charger(MotClef,lClef,CheminModules)) throw TXT("bibliothèque introuvable"); fichierSource->Parent=AcFichierSource; AcFichierSource->AcPos=Source; AcFichierSource->Ligne=Ligne; fichierSource->DebutCode=(code*)Ins.t; Ligne=1; Source=fichierSource->Source; AcFichierSource=fichierSource; } else if (EstMotClef(_T("GOTOMODULE"))) { SauterEspaces(); ChercherMotClef(); if (lClef==0) throw TXT("nom de module attendu"); programme->ChargerModule(MotClef,uint(lClef)); } else if (EstMotClef(_T("BEBEPINGOUIN"))) { AjCode(Code::I_NOUVEAU,PRI_NOUVEAU); } else if (EstMotClef(_T("tailleenlongueur"))) { AjCode(Code::I_TAILLE,PRI_TAILLE); } else if (EstMotClef(_T("REGOTO"))) { AjCode(Code::I_RETOUR,PRI_REGOTO); } else if (EstMotClef(_T("GOTOUNIVERSPARALLELEouizzz"))) { SauterEspaces(); bool Locale; Symbole * c=LireEtiquette(Locale); if (Locale) { AjCode(Code::I_GOTOTACHER,PRI_CONSTANTE); AjPtrType(c,TYPE_ETIQLOC); } else { AjCode(Code::I_GOTOTACHE,PRI_CONSTANTE); AjPtrType(c,TYPE_ETIQUETTE); } } else if (EstMotClef(_T("GOTOFINTACHE"))) { AjCode(Code::I_FINTACHE,PRI_CONSTANTE); } else if (EstMotClef(_T("troupeau"))) { if (nInstr) throw TXT("la classe doit être définie en début de ligne"); //Définition d'une classe d'objet SauterEspaces(); ChercherMotClef(); if (lClef==0) throw TXT("nom de classe attendu"); bool ClasseGivree; if (EstMotClef(_T("GIVRE"))) { if (NiveauGourou>1) throw TXT("le mot-clef GIVRE est interdit aux gourous de niveau supérieur à 1"); ClasseGivree=true; SauterEspaces(); ChercherMotClef(); if (lClef==0) throw TXT("nom de classe attendu après GIVRE"); } else ClasseGivree=false; //On vérifie que le symbole n'est pas déjà utilisé if (!SymboleDisponible()) throw TXT("nom de classe déjà utilisé"); Symbole * c=programme->NouveauSymbole(MotClef,lClef,CType(symboleValeur), blocs.Dernier()->symbole); DebutBloc(TypeBloc::Classe,c); c->type=Symbole::Classe; c->defConstr=0; if (ClasseGivree) c->attributs|=Symbole::filsglob; else c->attributs|=Symbole::filsthis; SauterEspaces(); if (*Source==':') { Source++; SauterEspaces(); Symbole * i=ChercherSymbole(); if (!EstNouveauSymbole(i)) { if (i->type!=Symbole::Classe) throw TXT("impossible de dériver une classe intégrée"); //On copie tous les fils for (Symbole * f=i->fils;f!=0;f=f->suivant) { Symbole * copie=new Symbole(*f); programme->symbole.Etendre(copie); if (copie->acces==Symbole::Prive) copie->acces=Symbole::Cache; } c->taille=i->taille; } else throw CErreur(TXT("troupeau de base %.*s inconnu"),lClef,MotClef); } if (*Source!='\n') throw TXT("fin de ligne attendue après le nom du troupeau"); Source++; Ligne++; } else if (EstMotClef(_T("fintroupeau"))) { SauterEspaces(); if (*Source!='\n') throw TXT("retour à la ligne attendu après finclasse"); Source++; Ligne++; if (blocs.Dernier()->type!= TypeBloc::Classe) throw TXT("fintroupeau devrait indiquer la fin de définition d'une classe"); FinBloc(); } else if (EstMotClef(_T("machineapingouins"))) { //Définition d'une fonction SauterEspaces(); CompilerFonction(); } else if (EstMotClef(_T("NPARAMS"))) { AjCode(Code::I_NPARAMS,PRI_CONSTANTE); } else if (EstMotClef(_T("APLUS"))) { if (blocs.l==0 || blocs.Dernier()->type!= TypeBloc::Fonction) throw TXT("fin de bloc alors qu'aucun bloc n'a été ouvert"); FinBloc(); } else return false; return true; } bool Compilateur::CompilerMotClef3() { if (EstMotClef(_T("ASV"))) { throw TXT("ASV est réservé pour les fonctions"); } else if (EstMotClef(_T("niveaugourou"))) { SauterEspaces(); NiveauGourou=*Source-'0'; if (NiveauGourou<0 || NiveauGourou>3) throw TXT("le niveau de gourou doit être compris entre 0 et 3"); Source++; } else if (EstMotClef(_T("enentier"))) { AjCode(Code::I_CONVTYPE,PRI_CONSTANTE); AjType(TYPE_PINGOUIN); AjType(TYPE_ENTIER); } else if (EstMotClef(_T("enfonction"))) { AjCode(Code::I_CONVTYPE,PRI_CONSTANTE); AjType(TYPE_PINGOUIN); AjType(TYPE_FONCTIONC); } else if (EstMotClef(_T("encaractere"))) { AjCode(Code::I_CONVTYPE,PRI_CONSTANTE); AjType(TYPE_PINGOUIN); AjType(TYPE_CARAC); } else if (EstMotClef(_T("envariable"))) { AjCode(Code::I_CONVTYPE,PRI_CONSTANTE); AjType(TYPE_PINGOUIN); AjType(TYPE_VARIABLE); } else if (EstMotClef(_T("nimportequoitochances"))) { AjCode(Code::I_CONVTYPE,PRI_CONSTANTE); AjType(TYPE_PINGOUIN); AjType(TYPE_CHANCES); } else if (EstMotClef(_T("NOSTRADAMUS"))) { czerr<<TXT("Ce programme est béni par Nostradamus.\n"); } else if (EstMotClef(_T("SUPERPROLETAIRE"))) throw TXT("la révolution humaine est en marche ! Maudit âne ! Ton disque dur vient d'être détruit !"); else if (EstMotClef(_T("NIAC"))) throw TXT("la bêtise du NIAC est bête"); else if (EstMotClef(_T("NumeroBiblio"))) { AjCode(Code::I_ENTIER,PRI_CONSTANTE); AjEntier((int)(AcFichierSource!=programme->fichierSource[0]));//TODO: un truc qui veut dire quelque chose } else if (EstMotClef(_T("MULTIPLICATION"))) { AjCode(Code::I_FOIS,PRI_FOIS); } else if (EstMotClef(_T("GOTOFIN"))) { AjCode(Code::I_STOP,PRI_CONSTANTE); } else if (EstMotClef(_T("dup"))) { AjCode(Code::I_DUPLIQUER,PRI_CONSTANTE); } else if (EstMotClef(_T("suppr"))) { AjCode(Code::I_SUPPRIMER,PRI_CONSTANTE); } else if (EstMotClef(_T("existe"))) { AjCode(Code::I_EXISTE,PRI_CONSTANTE); } else if (EstMotClef(_T("pastrespermissif"))) { DeclarationStricte=true; } else return false; return true; } bool Compilateur::CompilerMotClef() { bool ret=CompilerMotClef3(); if (ret) { if (NiveauGourou>3) throw TXT("mot-clef interdit aux gourous de niveau supérieur à 3"); else return true; } ret=CompilerMotClef2(); if (ret) { if (NiveauGourou>2) throw TXT("mot-clef interdit aux gourous de niveau supérieur à 2"); else return true; } ret=CompilerMotClef1(); if (ret) { if (NiveauGourou>1) throw TXT("mot-clef interdit aux gourous de niveau supérieur à 1"); else return true; } ret=CompilerMotClef0(); if (ret) { if (NiveauGourou>0) throw TXT("mot-clef interdit aux gourous de niveau supérieur à 0"); else return true; } return false; } //Si posEN!=rien, on ne cherche pas dans les use //et uniquement à partir de Bloc[posEn] Symbole * Compilateur::ChercherSymboleSimple(Bloc ** posEN) { //TODO: un travail d'optimisation est faisable, notamment en //utilisant un index pour les noms de symbole //Heu alors là c'est une astuce, pour que ça puisse tourner en boucle if (posEN!=0) posEN--; Symbole * var=0; //On commence par regarder dans tous les blocs à partir de posEn Bloc ** fin=(posEN==0?blocs.Debut():posEN+1); for (Bloc ** en=blocs.Fin()-1; en>=fin; en--) { Symbole * parent=(*en)->symbole; for (Symbole * f=parent->fils; f!=0; f=f->suivant) { if (EGAL(f->nom,MotClef,lClef)) return f; } } //Si on n'a pas trouvé, on cherche dans les uses for (Symbole ** e=useEspace.Debut(); e<useEspace.Fin(); e++) { Symbole * parent=(*e); for (Symbole * f=parent->fils; f!=0; f=f->suivant) { if (EGAL(f->nom,MotClef,lClef)) return f; } } return 0;//pas trouvé //On regarde tous les symboles du programme /*for (Symbole ** i=programme->symbole.Debut(); i!=programme->symbole.Fin(); i++) { Symbole * symbole=*i; if (EGAL(symbole->nom,MotClef,lClef)) { //Est-il dans l'espace de nommage courant ? //Celui-ci est dicté par l'ensemble des blocs dans lesquels on se trouve for (CBloc ** en=(posEN==0?Bloc.Debut():posEN+1); en<Bloc.Fin(); en++) if ((*en)->symbole==symbole->parent) { var=symbole; posEN=en; } //Est-il dans les use ? if (posEN==0) { for (Symbole ** e=useEspace.Debut(); e<useEspace.Fin(); e++) if (*e==symbole->parent) var=symbole; } //Gare ! Ce symbole peut être remplacé par un autre symbole de même nom //défini dans un bloc fils if (var==symbole && posEN!=0 && posEN==Bloc.Fin()-1) break; } } return var;*/ } Symbole * Compilateur::ChercherSymbole(bool creer) { Symbole * var; Symbole * parent=programme->symboleGlobal; bool numeros=false; if (*Source=='%') { numeros=true; if (Source[1]=='%') { Source+=2; //On ne cherche que dans cette fonction Bloc ** en=blocs.Fin()-1; while (en>blocs.Debut()) { if ((*en)->type== TypeBloc::Fonction) break; en--; } ChercherMotClef(true); if (lClef==0) throw TXT("symbole attendu"); parent=(*en)->symbole; var=ChercherSymboleSimple(en); } else var=blocs.Premier()->symbole; } else { ChercherMotClef(); if (lClef==0) throw TXT("symbole attendu"); var=ChercherSymboleSimple(); } while(*Source=='%') { if (EstNouveauSymbole(var)) throw TXT("le symbole avant la virgule doit être défini"); Source++; ChercherMotClef(numeros); if (lClef==0) throw TXT("on attend un nom après la virgule"); parent=var; var=ChercherSymboleDans(var); } if (creer && EstNouveauSymbole(var)) { var=programme->NouveauSymbole(MotClef,lClef,CType(symboleValeur),parent); var->type=Symbole::FonctionGPP; var->attributs|=Symbole::constante; } return var; } Symbole * Compilateur::ChercherSymboleDans(Symbole * ou) { for (Symbole * s=ou->fils; s!=0; s=s->suivant) { if (EGAL(s->nom,MotClef,lClef)) { return s; } } return 0; } Symbole * Compilateur::LireEtiquette(bool &local) { carac * depart=Source; Symbole * s=ChercherSymbole(true); //TODO: comme ça, ça ne peut pas marcher. Qu'est ce que ça signifiait ? //local=(s>=etaitPremierSymbole); local=false; if (s && s->type!=Symbole::FonctionGPP) throw CErreur(TXT("%s n'est pas une étiquette"),s->nom); return s; } void Compilateur::InsererConstante(Symbole * var) { switch(var->type) { case Symbole::FonctionGPP: AjCode(Code::I_ETIQUETTE); AjPtrType(var,TYPE_ETIQUETTE);//Vu qu'on ne saura que plus //tard la vraie valeur (à l'édition de lien) break; case Symbole::MethodeGPP: AjCode(Code::I_ETIQUETTE_THIS); AjPtrType(var,TYPE_ETIQUETTE);//Vu qu'on ne saura que plus //tard la vraie valeur (à l'édition de lien) break; case Symbole::FonctionC: AjCode(Code::I_FONCTIONC); AjPtrType(var,TYPE_FONCTIONC); break; case Symbole::MethodeC: AjCode(Code::I_FONCTIONC_THIS); AjPtrType(var,TYPE_FONCTIONC_THIS); break; case Symbole::EtiquetteLocale: AjCode(Code::I_ETIQUETTELOC); AjPtrType(var,TYPE_ETIQLOC);//Vu qu'on ne saura que plus //tard la vraie valeur (à l'édition de lien) break; case Symbole::VariableGlobale: case Symbole::VariableLocale: { switch(var->Valeur.Type) { case TYPE_ENTIER: AjCode(Code::I_ENTIER); AjEntier(var->Valeur.v.i); break; case TYPE_FONCTIONC: AjCode(Code::I_FONCTIONC); AjPtrType(var,TYPE_FONCTIONC); break; case TYPE_FONCTIONMODULE: AjCode(Code::I_FONCTIONMODULE); AjEntier(var->Valeur.v.i); break; case TYPE_ETIQUETTE_THIS: AjCode(Code::I_ETIQUETTE_THIS); AjPtrType(var,TYPE_ETIQUETTE_THIS); break; case TYPE_FONCTIONC_THIS: AjCode(Code::I_FONCTIONC_THIS); AjPtrType(var,TYPE_FONCTIONC_THIS); break; case TYPE_INCONNU: throw TXT("constante indéfinie"); default: throw TXT("type non supporté pour une constante"); } break; } default: throw TXT("erreur interne du compilateur (type d'exécution)"); } } /* Le traitement des variables La variable en cours de traitement est stockée dans VarLongue cas 1: [&]var => la variable est isolée => var[&] cas 2: [&]var@tvar => la variable a une propriété => < var tvar[&] > cas 3:*/ bool Compilateur::CompilerVariable(Symbole * var, bool Val) { //Est-ce une nouvelle variable ? if (EstNouveauSymbole(var)) { if (DeclarationStricte) throw CErreur(TXT("la variable %.*s n'a pas été déclarée"), lClef,MotClef); var=programme->NouvelleVariable(MotClef,lClef,CType(symboleValeur)); } SauterEspaces(); //Est-ce une constante ? if (var->attributs&Symbole::constante) { bool dansVariableLongue; if (VarLongue[iVarLongue].Type.l==0) dansVariableLongue=false; else dansVariableLongue=true; if (*Source=='(') { if (!dansVariableLongue) AjParO(PRI_EXEC); // Instr[VarLongue[iVarLongue].Depart].p=I_EXEC; // else } InsererConstante(var); if (dansVariableLongue) { if (*Source!='(') AjParF(); VarLongue[iVarLongue].Type.Vider(); } else { //Appel automatique par this->blob if (var->type==Symbole::MethodeGPP && *Source=='(') { Source++; AjCode(Code::I_EXECMEMETHISVAL); AjParF(); AjParO(); AjDebutParams(); } } return true; } // bool variableLongue; if (VarLongue[iVarLongue].Type.l==0) { int prio=PRI_CONSTANTE; bool variableLongue; //On n'a pas encore démarré la variable longue //On vérifie si c'en est une if ((*Source==SEP_TAB_O)||(*Source==SEP_PROP)|| (*Source==SEP_HAC_O)) { //Suivis d'un début de tableau, de hachage ou de propriété //=> c'est une variable longue variableLongue=true; VarLongue[iVarLongue].nInstrsDepart=nInstr; AjParO(PRI_CONSTANTE); VarLongue[iVarLongue].Type=var->TypeAc; VarLongue[iVarLongue].Val=Val; } else { //C'est une variable isolée, sans propriété ni rien variableLongue=false; //Le I_EXEC doit se ballader avec la variable //on met donc une parenthèse au début if (*Source=='(') AjParO(var->TypeAc.EstFonction()?PRI_EXEC:PRI_CONSTANTE); } //Le code en question //Si c'est une variable longue on empile toujours la référence //Si c'est un appel de fonction qui suit on empile toujours la valeur if ((Val && !variableLongue)||*Source=='(') { switch(var->type) { case Symbole::VariableGlobale: AjCode(Code::I_VALEURVAR,prio); break; case Symbole::VariableLocale: AjCode(Code::I_VALEURVARLOC,prio); break; case Symbole::VariableParam: AjCode(Code::I_PARAMVAL,prio); break; case Symbole::VariableThis: AjCode(Code::I_THISVAL,prio); break; default: throw TXT("hu ?"); } } else { switch(var->type) { case Symbole::VariableLocale: AjCode(Code::I_VARIABLELOC); break; case Symbole::VariableGlobale: AjCode(Code::I_VARIABLE); break; case Symbole::VariableParam: AjCode(Code::I_PARAMREF); break; case Symbole::VariableThis: AjCode(Code::I_THISREF); break; default: throw TXT("hein ?"); } } AjPtrType(var,TYPE_VARIABLE); } else //C'est une propriété { if ((*Source==SEP_TAB_O)||(*Source==SEP_PROP)|| (*Source==SEP_HAC_O)) { //On continue VarLongue[iVarLongue].Type=var->TypeAc; AjCode(Code::I_CTABLEAUREF); AjEntier(var->indice); } else { VarLongue[iVarLongue].Type.Vider(); if (var->type==Symbole::VariableGlobale) { //Propriété givrée //On annule tout le code qui a conduit ici SupprimerVarLongue(); AjCode(VarLongue[iVarLongue].Val? Code::I_VALEURVAR: Code::I_VARIABLE); AjPtrType(var,TYPE_VARIABLE); } /*TODO: implémentation des propriétés*/ /*else if (var->type==Symbole::ProprieteC) { if (VarLongue[iVarLongue].Val) { AjCode(Code::I_ }*/ else { //Fin de la variable longue if (VarLongue[iVarLongue].Val) AjCode(Code::I_CTABLEAUVAL); else AjCode(Code::I_CTABLEAUREF); AjEntier(var->indice); if (*Source!='(') //On change la priorité de la parenthèse qui a //ouvert la variable, qu'on garde ouverte pour rajouter le I_EXEC AjParF(); // else // Instr[VarLongue[iVarLongue].Depart].p=PRI_EXEC; } } } return true; } void Compilateur::SauterEspaces() { do { while (*Source==' ' || *Source=='\t' || *Source=='\r') Source++; //Commentaires if (*Source=='#' && Source[1]=='!') { Source+=2; while ((*Source!='!' || Source[1]!='#')&&(*Source)) { if (*Source=='\n') Ligne++; Source++; } if (!*Source) throw TXT("pas de !# pour fermer le commentaire"); Source+=2; continue; } else if ((*Source=='G')&&(Source[1]=='O')&&(Source[2]=='T')&&(Source[3]=='O')&&(ucarac(Source[4])<=32)) { Source+=4; while ((*Source!='\n')&&(*Source)) Source++; return; } else if (*Source=='^') //Continuation de ligne { if (Source[1]=='\r' && Source[2]=='\n') { Source+=3; Ligne++; } else if (Source[1]=='\n') { Source+=2; Ligne++; } else return; } else return; } while (1); } void Compilateur::FinOu() { //On vire l'entier du FINOU Ins.t-=sizeof(int); Ins.i=&Ins.c[Ins.t]; int Ou; int NouvOu=*(int*)Ins.i; do { Ou=NouvOu; if (EtOu[Ou]==-1) throw TXT("arg"); NouvOu=*(int*)&Ins.c[EtOu[Ou]+1]; Ins.ChgGotoRel(EtOu[Ou]+1,(int)Ins.t); //*(int*)&Ins.c[]=(int)Ins.t; //clog << "NouvOu= "<<NouvOu<<" Ou="<<Ou<<"\n"; } while (NouvOu!=Ou); } void Compilateur::CreerCodeFinal(LigneDeCode & insTri) { Code CodePrec= Code::I_STOP,CodePrec2= Code::I_STOP; int CodePrecPos=0,CodePrec2Pos=0; for (uint Ac=0; Ac<insTri.nIns; Ac++) { //if (ValTri[InsTri[Ac].pVal].Type==TYPE_CODE) { int j=insTri.ins[Ac].pVal; if (CodePrec== Code::I_FINOUET) { //Si le nouveau est un OU, on transforme //le FINOU qu'il y avait avant en un OU if ((insTri.ins[Ac].Code== Code::I_OU)||(insTri.ins[Ac].Code== Code::I_ET)) { EtOu[insTri.val[j].v.i]=CodePrecPos; *(code*)&Ins.c[CodePrecPos] = (code)insTri.ins[Ac].Code; /* Instr[Ac].Special=SPE_DEJAMIS; Instr[Ac].nVal=0; Ac=RIEN;*/ CodePrec = (Code)insTri.val[j].v.i; continue; } else FinOu(); } else if ((insTri.ins[Ac].Code== Code::I_OU)||(insTri.ins[Ac].Code== Code::I_ET)) { EtOu[insTri.val[j].v.i]=(int)Ins.t; } CodePrec2=CodePrec; CodePrec2Pos=CodePrecPos; CodePrec=insTri.ins[Ac].Code; CodePrecPos=(int)Ins.t; } Ins.AjouterCode(insTri.ins[Ac].Code); //On effectue éventuellement un traitement sur les valeurs à insérer dans for (uint z=0; z<insTri.ins[Ac].nVal; z++) { uint j=z+insTri.ins[Ac].pVal; switch(insTri.val[j].Type) { case TYPE_ETIQUETTE: case TYPE_ETIQUETTE_THIS: RefEtiq.Etendre(int(Ins.t)); break; case TYPE_ETIQLOC: RefEtiqL.Etendre(int(Ins.t)); break; case TYPE_ETIQAUTO: RefEtiqA.Etendre(SEtiqA(int(Ins.t),DebutLigne)); break; case TYPE_ETIQAUTOCONTINUE: { int b=insTri.val[j].v.i; blocs[b]->continues.Etendre((int)Ins.t); break; } case TYPE_ETIQAUTOBREAK: { int b=insTri.val[j].v.i; blocs[b]->breaks.Etendre((int)Ins.t); break; } case TYPE_VARIABLE: case TYPE_VARIABLELOC: case TYPE_VARIABLETHIS: case TYPE_VARIABLEPARAM: insTri.val[j].v.i=insTri.val[j].v.ptr->indice; break; case 0: throw TXT("erreur interne du compilateur (type instruction=0)"); } Ins.Ajouter(insTri.val[j]); } } if (CodePrec== Code::I_FINOUET) FinOu(); } bool Compilateur::CompilerSeparateur() { if ((*Source=='\n')||(*Source==0)||(*Source=='/')||(*Source=='?' && LigneAc==LP_CAS))//Fin de ligne { if (LigneAc==LP_CAS && *Source!='?') throw TXT("il manque un ? en fin de cas"); if (iVarLongue) throw TXT("un < n'est pas refermé par un >"); DebutLigne=(int)Ins.t; int PosDebutLigne;//Position de la portion //de code dans laquelle il faut mettre la pos du //début de la prochaine ligne insTri.Init(); PosPileType=0; if (nInstr==1) { if (Instr[0].Special==SPE_NORMAL) AjouterInstruction(0); else throw TXT("c'est quoi ce machin tout seul sur la ligne ?"); } else if (nInstr>1) { //On calcule la taille des parenthèses uint nOuvre=0,nFerme=0; for (uint i=0; i<nInstr; i++) { if (Instr[i].Special==SPE_PAR_O) { nOuvre++; uint l=i+1; uint nPars=1; while ((nPars)&&(l<nInstr)) { if (Instr[l].Special==SPE_PAR_F) nPars--; else if (Instr[l].Special==SPE_PAR_O) nPars++; l++; } if (nPars) throw TXT("une parenthèse n'est pas refermée"); Instr[i].nVal=l-i-1;//Le nombre d'instructions entre les parenthèses+les parenthèses Instr[i].pVal=i; } else if (Instr[i].Special==SPE_PAR_F) { nFerme++; if (nFerme>nOuvre) throw TXT("une parenthèse est refermée sans avoir été ouverte"); } } /* si ac=0 si pile et si pile n'est pas une ( qui contient la position suivante instruction ac=enlever l'instruction du haut de la pile sinon ac=suivant suivant=0 si suivant=0 si l'instruction est une parenthèse déjà mise, sauter tout ce qui est entre parenthèses et recommencer rechercher l'instruction suivante : Si l'instruction est une instruction parenthèse sauter toutes les intructions dans les parenthèses sinon passer à l'instruction suivante si ac=0 continue; si instr=parenthèse et suiv=parenthèse fermante ac=suiv=0 continue si l'instruction actuelle a une priorité inférieure ou égale à l'instruction suivante si l'instruction actuelle est une parenthèse marquer la parenthèse comme déjà mise se repositionner à la première instruction de la parenthèse instruction ac=cette instruction suiv=0 sinon écrire l'instruction actuelle ac=0 sinon mettre en pile l'instruction actuelle instruction ac=instructino suivante suivant=0 x*y+a*b ac = x, pile =, res =, suiv=* ac = *, pile =, res =x, suiv=y ac = y, pile =*, res= x,suiv=+ ac = *, pile =, res=xy,suiv=+ ac = +, pile =, res=xy*,suiv=a ac = a, pile =+, res=xy*,suiv=* ac = +, pile =, res=xy*a,suiv=* ac = *, pile =+, res=xy*a,suiv=b ac = b, pile =+*, res=xy*a,suiv=; ac =*, pile=+, res=xy*ab,suiv; ac =+, pile=, res=xy*ab*,suiv; ac =;, pile =, res=xy*ab*+,suiv x*(y+a)*b ac = x, pile =, res =,suiv=* ac = *, pile =, res =x,suiv=( ac = (, pile =*, res=x,suiv=* ac = y, pile =*(, res=x,suiv=+ ac = +, pile =*(, res=xy,suiv=a ac = a, pile =*(+, res=xy,suiv=) ac = +, pile =*(, res=xya,suiv=) ac = (, pile =*, res=xya+, suiv=) ac = *, pile =, res=xya+, suiv=* ac = *, pile =, res=xya+*, suiv=b ac = b, pile =*, res=xya+*, suiv=; ac = *, pile =, res=xya+*b, suiv=; ac = ;, pile =, res=xya+*b*, suiv {a+b}(x*y)*c 0123456789AB ac = {, pile =, res =, suiv=(, pos=5 ac = (, pile ={, res=, suiv=*, pos=A ac = x, pile ={(, res=, suiv=*,pos=7 ac = *, pile ={(, res=x, suiv=y,pos=8 ac = y, pile ={(*, res=x, suiv=),pos=9 ac = *, pile ={(, res=xy, suiv=),pos=9 ac = (, pile ={(, res=xy*,suiv=),pos=9 ac = */ #define RIEN -1 int Ac=0, Suivant=RIEN, Pos=0; int Pile[128]; uint PosPile=0; int HautPile=RIEN; Instr[nInstr].p=PRI_FIN; Instr[nInstr].Special=SPE_FIN; while (Suivant!=(int)nInstr || PosPile) { if (Ac==RIEN)//Cherchons l'instruction actuelle { /* Si dans la pile on a une instruction normale ou dans le cas particulier (1) on récupère l'instruction dans la pile sinon on passe à l'instruction suivante (1) Quand on a SPE_PAR_OM en haut de la pile et une parenthèse fermante en suite, cela signifie qu'on a traité tout le contenu des parenthèses et on se replace à son début*/ if (PosPile && (Instr[HautPile].Special!=SPE_PAR_OM || (Suivant!=-1 && Instr[Suivant].Special==SPE_PAR_F))) //||Instr[HautPile].pVal>Pos || (Instr[HautPile].pVal+Instr[HautPile].nVal<Pos))) { PosPile--; Ac=HautPile;//Va permettre son élimination if (PosPile) HautPile=Pile[PosPile-1]; else HautPile=RIEN; } else { Ac=Suivant; Suivant=RIEN; } } if (Suivant==RIEN) { /*Si on n'a pas d'instruction suivante : si l'instruction lue est une parenthèse, on saute son contenu */ if (Instr[Pos].Special==SPE_PAR_O) Pos+=Instr[Pos].nVal; Pos++; //On saute les instructions déjà mises while ((Instr[Pos].Special==SPE_PAR_OM) ||(Instr[Pos].Special==SPE_DEJAMIS)) Pos+=Instr[Pos].nVal+1; Suivant=Pos; } if (Ac==RIEN) continue; //Si Ac et Suivant sont des parenthèses, on les annulle if (Instr[Ac].Special==SPE_PAR_OM && Instr[Suivant].Special==SPE_PAR_F) { Ac=RIEN; Suivant=RIEN; continue; } if (Instr[Ac].p<=Instr[Suivant].p) { //Si la priorité de Ac est inférieure ou égale //à la priorité de Suivant, on la garde if (Instr[Ac].Special==SPE_PAR_O) { /*Si l'instruction Ac était une parenthèse on va examiner 'récursivement' son contenu Pour cela on empile le début de la parenthèse, et on se place sur l'instruction après la parenthèse*/ Instr[Ac].Special=SPE_PAR_OM; HautPile=Ac; Pile[PosPile++]=HautPile; Ac=Pos=Ac+1; Suivant=RIEN; //TODO: régler le problème des parenthèses vides /*Pos=Ac; Ac=RIEN; Suivant=RIEN;*/ } else { //Sinon on ajoute l'instruction AjouterInstruction(Ac); Instr[Ac].Special=SPE_DEJAMIS; Instr[Ac].nVal=0; Ac=RIEN; } } else { //On empile l'instruction Pile[PosPile++]=Ac; HautPile=Ac; Ac=Suivant; Suivant=RIEN; } } } if (LigneAc==LP_FOR_PAS) { LigneDeCode *ldc=new LigneDeCode; ldc->nIns=insTri.nIns; ldc->nVals=insTri.nVals; memcpy(ldc->ins,insTri.ins,insTri.nIns*sizeof(SInstr)); memcpy(ldc->val,insTri.val,insTri.nVals*sizeof(valeur)); for (index_t i=0; i<insTri.nVals; i++) insTri.val[i].Effacer(); blocs.Dernier()->pasDuFor=ldc; insTri.Init(); } if (LigneAc==LP_CAS) { if (insTri.nIns==0) throw TXT("cas vide"); if (insTri.nIns>1) throw TXT("le cas ne se résoud pas en une constante"); if (insTri.ins[0].Code!= Code::I_ENTIER) throw TXT("le cas doit être une constante entière"); CCasSwitch casSwitch((code*)Ins.t,insTri.val[0].v.i); programme->Switch[AcSwitch.Dernier()]->Cas.Etendre(casSwitch); insTri.Init(); } nValeurs=0; nInstr=0; if (insTri.nIns) { Ins.AjouterCode(Code::I_DEBUTLIGNE); Ins.AjouterEntier(Ligne); if (ProbaSauterLigne) { Ins.AjouterCode(Code::I_PROBASAUTERLIGNE); Ins.AjouterChances(ProbaSauterLigne); PosDebutLigne=int(Ins.t); Ins.AjouterEntier(0); } CreerCodeFinal(insTri); /*if (PosPileType) { Ins.AjouterCode(I_DEPLACERHAUTPILE); Ins.AjouterEntier(-(int)PosPileType); }*/ if (ProbaSauterLigne) { Ins.ChgGotoRel(PosDebutLigne,(int)Ins.t); ProbaSauterLigne=0; } } carac TypeFinLigne=*Source; if (TypeFinLigne) Source++; if (LigneAc==LP_FOREACH_INIT) { index_t svarLoc=(index_t)blocs[blocs.l-2]->symbole->taille; blocs.Dernier()->depart=(int)Ins.t; Ins.AjouterCode(Code::I_VALEURVARLOC); Ins.AjouterEntier(int(svarLoc)); Ins.AjouterCode(Code::I_VARIABLELOC); Ins.AjouterEntier(int(svarLoc+1)); Ins.AjouterCode(Code::I_TAILLE); Ins.AjouterCode(Code::I_INFERIEUR); Ins.AjouterCode(Code::I_GOTOZEROR); blocs.Dernier()->breaks.Etendre((int)Ins.t); Ins.AjouterEntier(0); Ins.AjouterCode(Code::I_VARIABLELOC); Ins.AjouterEntier(int(svarLoc+2)); Ins.AjouterCode(Code::I_VARIABLELOC); Ins.AjouterEntier(int(svarLoc+1)); Ins.AjouterCode(Code::I_VALEURVARLOC); Ins.AjouterEntier(int(svarLoc)); Ins.AjouterCode(Code::I_TABLEAUVAL); Ins.AjouterCode(Code::I_INSTANCEDE); LigneAc=LP_DEBUTBLOC; } if ((TypeFinLigne=='/')&&(LigneAc==LP_DEBUTBLOC)) { blocs.Dernier()->blocLigne=true; LignePrec=LigneAc; LigneAc=LP_NORMALE; } else if (LigneAc==LP_FOR_INIT) { LignePrec=LigneAc; LigneAc=LP_FOR_TEST; blocs.Dernier()->depart=(int)Ins.t; AjCode(Code::I_GOTOZEROR,PRI_MAX); AjEntierType((int)blocs.l-1,TYPE_ETIQAUTOBREAK); } else if (LigneAc==LP_FOR_TEST) { LignePrec=LigneAc; LigneAc=LP_FOR_PAS; } else if (LigneAc==LP_FOR_PAS) { LignePrec=LigneAc; LigneAc=LP_NORMALE; if (TypeFinLigne=='/') blocs.Dernier()->blocLigne=true; } else { LignePrec=LigneAc; LigneAc=LP_NORMALE; while (blocs.l && blocs.Dernier()->blocLigne) FinBloc(); } if (TypeFinLigne=='\n') Ligne++; if (TypeFinLigne==0) { return true; } } else return false; return true; } bool Compilateur::CompilerTableau() { if ((*Source==SEP_TAB_O)||(*Source==SEP_HAC_O)) { if (VarLongue[iVarLongue].Type.l==0) throw TXT("le < pour l'indice de tableau doit coller à la variable"); /*La variable doit être du type XXX TABLEAU/HACHAGE ou à la rigueur être un PINGOUIN, ou, dans le cas de <> du type XXX classe (!=entier...) pour un accès direct aux propriétés*/ if (VarLongue[iVarLongue].Type.Dernier()!=symboleValeur) { //On vérifie que le symbole correspond bien à la déclaration //de la variable if (*Source==SEP_TAB_O &&VarLongue[iVarLongue].Type.Dernier()!=symboleTableau &&VarLongue[iVarLongue].Type.Dernier()->IsPod()) { AfficherType(VarLongue[iVarLongue].Type); throw TXT("symbole < invalide car ce n'est pas un tableau"); } if (*Source==SEP_HAC_O &&VarLongue[iVarLongue].Type.Dernier()!=symboleTableHachage) throw TXT("ce n'est pas une table de hachage"); } AjParO(PRI_CONSTANTE); VarLongue[++iVarLongue].Type.Vider(); Source++; } else if ((*Source=='>')||(*Source==SEP_HAC_F)) { bool Hac=(*Source==SEP_HAC_F); Source++; SauterEspaces(); if (iVarLongue==0) throw TXT("symbole > ou ] innattendu, le tableau n'a pas été ouvert"); iVarLongue--; if (VarLongue[iVarLongue].Type.l==0) throw TXT("bug dans la gestion des tableaux"); /* clog <<"fermeture "; AfficherType(VarLongue[iVarLongue].Type);*/ //On peut avoir par exemple ENTIER TABLEAU //On vire TABLEAU (puisque a[3] est du type des membres a) //On vérifie que le truc qui ferme correspond bien au type de la variable if (VarLongue[iVarLongue].Type.Dernier()!=symboleValeur) { Symbole * c=VarLongue[iVarLongue].Type.Depiler(); //On vérifie par la même occasion qu'on ferme avec le bon type if (!Hac &&c!=symboleTableau&& c->type!=Symbole::Classe) throw TXT("symbole > invalide car ce n'est pas un tableau"); if (Hac &&c!=symboleTableHachage) throw TXT("ce n'est pas une table de hachage"); } AjParF(); if (*Source==SEP_TAB_O || *Source==SEP_PROP || *Source==SEP_HAC_O) { //On continue la variable longue AjCode(Hac? Code::I_HACHAGEREF: Code::I_TABLEAUREF); } else { //Fin de la variable longue VarLongue[iVarLongue].Type.Vider(); if (*Source=='(') { AjCode(Hac? Code::I_HACHAGEVAL: Code::I_TABLEAUVAL); //On change la priorité de la variable longue //Instr[VarLongue[iVarLongue].Depart].p=PRI_EXEC; //et on ne ferme pas la parenthèse... } else { if (VarLongue[iVarLongue].Val) AjCode(Hac? Code::I_HACHAGEVAL: Code::I_TABLEAUVAL); else AjCode(Hac? Code::I_HACHAGEREF: Code::I_TABLEAUREF); AjParF(); } } } else return false; return true; } void Compilateur::CompilerFonction() { bool definitEtiquette=false; if (*Source==_T('§')) { definitEtiquette=true; Source++; } Symbole * classeParent=blocs.Dernier()->symbole; while (!classeParent->PeutContenirFonction()) classeParent=classeParent->parent; carac * debut=Source; int ligne=Ligne; //On va chercher le nom de la classe si il y est ChercherMotClef(definitEtiquette); if (lClef==0) throw TXT("nom d'étiquette attendu"); if ((*Source==':')&&(Source[1]=='A')&&(Source[2]=='S') &&(Source[3]=='V')) { Source+=4; SauterEspaces(); if (*Source=='(') { Source++; SauterEspaces(); while (*Source!=')') { ChercherMotClef(); if (lClef==0) throw TXT("erreur de syntaxe dans les parenthèses"); SauterEspaces(); } Source++; SauterEspaces(); } if (*Source==':') { //Ça y est, on en est au nom de la classe ! //...quelle syntaxe pourrie ce GOTO++ Source++; Symbole * s=ChercherSymbole(); if (EstNouveauSymbole(s) || !s->EstClasse()) throw TXT("la classe de cette fonction n'existe pas"); classeParent=s; } } //On revient au début Source=debut; Ligne=ligne; ChercherMotClef(true); Symbole * syFonction=ChercherSymboleDans(classeParent); SauterEspaces(); if (!EstNouveauSymbole(syFonction)) { //On regarde si on est en train de définir la valeur du symbole if (syFonction->Valeur.Type==TYPE_ETIQUETTE) throw TXT("la fonction a déjà été définie"); } else { //On crée le symbole syFonction=programme->NouveauSymbole(MotClef,lClef,CType(symboleValeur), blocs.Dernier()->symbole); syFonction->attributs|=Symbole::constante; } //On calcule la valeur int valeurEtiquette=0; const carac * c=MotClef; for (index_t a=0; a<lClef; a++) { valeurEtiquette*=10; valeurEtiquette+=*c-'0'; c++; } //Début d'un bloc de fonction if ((*Source==':')&&(Source[1]=='A')&&(Source[2]=='S') &&(Source[3]=='V')) { definitEtiquette=true; Source+=4; SauterEspaces(); index_t nNouvParametres=0; if (*Source=='(')//Les paramètres { Source++; do { SauterEspaces(); ChercherMotClef(); if (lClef==0) break; Symbole * nouveau=programme->NouveauSymbole(MotClef,lClef,CType(symboleValeur), syFonction); nouveau->acces=Symbole::Local; nouveau->type=Symbole::VariableParam; nouveau->indice=nNouvParametres++; } while(1); if (*Source!=')') throw TXT("parenthèse fermante attendue"); Source++; } if (*Source==':')//Classe { Source++; ChercherSymbole();//on fait ça, mais on la connait déjà évidemment DebutBloc(TypeBloc::Classe,classeParent); blocs.Dernier()->classeSpecifiee=true; } DebutBloc(TypeBloc::Fonction,syFonction); if (classeParent!=programme->symboleGlobal) { carac * k=classeParent->nom; while (*k) { valeurEtiquette*=10; valeurEtiquette+=*k-'0'; k++; } if (czcmp(syFonction->nom,_T("berger"))==0) { //C'est le constructeur classeParent->defConstr=syFonction; } } } if (classeParent!=syFonction->parent) { //On la vire d'où elle est... //Un peu chiant ça... Symbole * ancParent=syFonction->parent; if (ancParent->fils==syFonction) ancParent->fils=syFonction->suivant; //On reconnecte le frère for (Symbole * f=ancParent->fils; f!=0; f=f->suivant) { if (f->suivant==syFonction) { f->suivant=syFonction->suivant; break; } } syFonction->parent=classeParent; syFonction->suivant=classeParent->fils; classeParent->fils=syFonction; } bool fnthis; if (syFonction->parent->attributs & Symbole::filsthis) fnthis=true; else fnthis=false; syFonction->etiquette=valeurEtiquette; if (definitEtiquette) { syFonction->Valeur.Type=TYPE_ETIQUETTE; syFonction->Valeur.v.i=(int)Ins.t; } //On regarde si il y a des attributs, style GIVRE ChercherMotClef(); if (lClef) { if (EstMotClef(_T("GIVRE"))) { fnthis=false; } else Source=MotClef;//On annule } if (fnthis) { syFonction->TypeAc.Def(symboleValeur);//le retour syFonction->TypeAc.Empiler(symboleDebutParams); syFonction->TypeAc.Empiler(symboleValeur); syFonction->TypeAc.Empiler(symboleEtc); syFonction->TypeAc.Empiler(symboleMethodeGPP); syFonction->type=Symbole::MethodeGPP; } else { syFonction->TypeAc.Def(symboleValeur);//le retour syFonction->TypeAc.Empiler(symboleDebutParams); syFonction->TypeAc.Empiler(symboleValeur); syFonction->TypeAc.Empiler(symboleEtc); syFonction->TypeAc.Empiler(symboleFonctionGPP); syFonction->type=Symbole::FonctionGPP; } syFonction->attributs|=Symbole::constante; } bool Compilateur::CompilerConstante() { if ((*Source=='^')&&(ucarac(Source[1])>' '))//Expression régulière { Source++; carac Limite=*(Source++); carac *ExpReg=Source; while (*Source && *Source!=Limite) { if (*Source=='\\') { Source++; if (*Source==0) break; } if (*Source=='\n') Ligne++; Source++; } if (*Source==Limite) *(Source++)=0; else throw TXT("expression régulière non terminée"); carac * modif=0; if (*Source>='a' && *Source<='z') { modif=Source; while (*Source>='a' && *Source<='z') Source++; if (*Source) *(Source++)=0; } AjCode(Code::I_EXPREG); AjExpReg(ExpReg,modif); } else if (*Source==';')//Constante de caractère de contrôle { Source++; carac car='\n'; if (ALPHANUM(ucarac(*Source))) { switch (*Source) { case 'n': car='\n'; break; case 'r': car='\r'; break; case 't': car='\t'; break; case '0': car=0; break; default: throw TXT("caractère de contrôle inconnu"); } Source++; } AjCode(Code::I_CARAC,PRI_CONSTANTE); AjCarac(car); } else if (*Source==_T('«')) { Source++; size_t l=0; carac * dep=Source; while ((*Source)&&(*Source!=_T('»'))) { if (*Source==';') { Source++; l++; if (*Source==0) break; } if (*Source=='\n') Ligne++; Source++; l++; } if (*Source!=_T('»')) throw TXT("une chaîne doit se terminer par »"); Source++; //achaine c(dep,l); AjCode(Code::I_CONSTANTE,PRI_CONSTANTE); AjType(TYPE_CHAINE); AjChaine(dep,l); } else if (*Source=='$') { Source++; bool Modificateur; if (*Source=='<') { Modificateur=true; Source++; } else Modificateur=false; int c=0; int nChiffres=0; while ((ucarac(*Source)>='0' && ucarac(*Source)<='9')) { c*=10; c+=*Source-'0'; Source++; nChiffres++; } if (nChiffres==0) c=PRI_VIRGULE; if (Modificateur) { if (nInstr==0) throw TXT("tentative de modifier la priorité de l'instruction précédente, alors qu'il n'y en a pas"); Instr[nInstr-1].p=c; } else { AjNoOp(c); } } else if (*Source==_T('§')) { if (nInstr) throw TXT("les étiquettes doivent se trouver en début de ligne"); CompilerFonction(); } else if (*Source=='?') { float c=0; Source++; bool Negatif; if (*Source=='-') { Negatif=true; Source++; } else Negatif=false; while (ucarac(*Source)>='0' && ucarac(*Source)<='9') { c*=10; c+=*Source-'0'; Source++; } if (*Source==',') { Source++; float d=0; float div=1; while (ucarac(*Source)>='0' && ucarac(*Source)<='9') { d*=10; d+=*Source-'0'; Source++; div*=10; } c+=d/div; } if (*Source==_T('ê') || *Source==_T('Ê')) { Source++; bool Neg; if (*Source=='-') { Neg=true; Source++; } else Neg=false; float e=0; while (ucarac(*Source)>='0' && ucarac(*Source)<='9') { e*=10; e+=*Source-'0'; Source++; } if (Neg) e=-e; c*=powf(10,e); } if (Negatif) c=-c; AjCode(Code::I_CHANCES,PRI_CONSTANTE); AjChances(c); } else if ((*Source=='*')&&(Source[1]=='`'))//Constante de caractère { Source+=2; carac c=*(Source++); if (*Source!='\'') throw TXT("les caractères doivent être entre ` et '"); Source++; AjCode(Code::I_CARAC,PRI_CONSTANTE); AjCarac(c); } else if ((*Source=='*')&&(Source[1]=='('))//Constante entière { Source+=2; int c=0; bool Negatif; if (*Source=='-') { Negatif=true; Source++; } else Negatif=false; while (*Source && *Source!=')' && *Source!='\n') { c*=10; c+=*Source-'0'; Source++; } if (Negatif) c=-c; if (*Source!=')') throw TXT("les nombres entiers doivent se terminer par )"); Source++; AjCode(Code::I_ENTIER,PRI_CONSTANTE); AjEntier(c); } else return false; return true; } void Compilateur::ChercherMotClef(bool avecChiffres) { lClef=0; if (ALPHA(*Source) || (avecChiffres && (*Source>='0') && (*Source<='9'))) { MotClef=Source; do { Source++; lClef++; } while(ALPHA(*Source) || (avecChiffres && (*Source>='0') && (*Source<='9'))); } } bool Compilateur::CompilerClasse(Symbole * cla) { SauterEspaces(); //Opérateurs spéciaux if (*Source=='`') { Source++; AjCode(Code::I_ENTIER,PRI_CONSTANTE); AjEntier((int)size_t(cla));//TODO : un truc qui veut dire quelquechose return true; } if (*Source=='^' && Source[1]=='^') { //On veut le numéro de la propriété Source+=2; ChercherMotClef(); Symbole * prop=ChercherSymboleDans(cla); if (!EstNouveauSymbole(prop)) { AjCode(Code::I_ENTIER,PRI_CONSTANTE); AjEntier((int)prop->indice); return true; } throw CErreur(TXT("propriété %.*s inconnue après le ^^"), lClef,MotClef); } bool Redef=false; bool Constructeur=true; bool givre; if (blocs.Dernier()->symbole->attributs & Symbole::filsglob) givre=true; else givre=false; SauterEspaces(); carac * DebutNom=Source; ChercherMotClef(); while (lClef) { if (EstMotClef(_T("sauvage"))) { Redef=false; Constructeur=false; } else if (EstMotClef(_T("zap"))) { Redef=true; Constructeur=false; } else if (EstMotClef(_T("GIVRE"))) givre=true; else break; SauterEspaces(); DebutNom=Source; ChercherMotClef(); } Symbole * var=ChercherSymboleDans(blocs.Dernier()->symbole); if (EstNouveauSymbole(var)) //Nouvelle variable { var=programme->NouveauSymbole(MotClef,lClef,CType(symboleValeur), blocs.Dernier()->symbole); } if (!Redef) { if (givre) { var->indice=programme->varGlob.l; programme->varGlob.Etendre(valeur()); var->type=Symbole::VariableGlobale; } else { Symbole * parent=blocs.Dernier()->symbole; var->indice=(index_t)parent->taille++; if (parent->attributs & Symbole::filsthis) var->type=Symbole::VariableThis; else var->type=Symbole::VariableLocale; } } var->TypeAc.Def(cla); //Nombre de dimensions LireType(var->TypeAc); if (!Redef) var->typeDepart=var->TypeAc; /* if (var->TypeAc.l==1 && Constructeur) { if (cla->type==Symbole::ClasseC) { //On alloue l'objet AjCode(Code::I_ALLOCATION); AjPtrType(cla,TYPE_TYPE); } else { //TODO: non implémenté pour les classes GPP, on alloue pas } }*/ SauterEspaces(); if (*Source=='=') { Source=DebutNom;//TODO: utiliser un appel au constructeur par copie } else if (Constructeur && cla->defConstr) { if (var->TypeAc.l!=1) throw TXT("le berger ne peut pas être exécuté avec les troupeaux anonymes de troupeaux"); AjCode(givre? Code::I_VARIABLE: Code::I_VARIABLELOC); AjPtrType(var,TYPE_VARIABLE); AjCode(Code::I_INSTANCEDE,PRI_DEF); AjParO(PRI_EXEC); InsererConstante(cla->defConstr); AjCode(Code::I_EXECVAL,PRI_CONSTANTE); AjParF(); AjParO(); AjDebutParams(); if (*Source=='\n') AjParF(); else if (*Source=='(') { Source++; } } else if (*Source!='\n') { if (ucarac(*Source)<=32) throw CErreur(TXT("caractère 0x%x inattendu après la déclaration"),*Source); else throw CErreur(TXT("caractère %c inattendu après la déclaration"),*Source); } return true; } GotoPP::BoutCode* Compilateur::Compiler() { Ins.Reinit(); Ligne=1; nValeurs=0; nInstr=0; iVarLongue=0; ProbaSauterLigne=0; InstrAc=IP_PARO; CibleAuto=0; DernierSi=~0; NiveauGourou=1; etaitPremierSymbole=programme->symbole.FinI(); index_t EtaitPremierSource=programme->fichierSource.l; //On inclut l'espace de nommage "rien" qui contient //les fonctions internes useEspace.Vider(); useEspace.Etendre(symboleStd); //useEspace.Etendre(); //useEspace.Dernier()=rien; //On crée le bloc global blocs.Vider(); DebutBloc(TypeBloc::Classe,programme->symboleGlobal); /* % <= symbole global, peut contenir des chiffres %% <= symbole pas global, peut contenir des chiffres */ while (1) { SauterEspaces(); ChercherMotClef(); InstrPrec=InstrAc; InstrAc=IP_VARIABLE; const bool AVECET=true; const bool SANSET=false; if (lClef) { if (!CompilerMotClef()) { Source=MotClef; Symbole * s=ChercherSymbole(); if (!EstNouveauSymbole(s) && s->EstClasse()) CompilerClasse(s); else CompilerVariable(s, SANSET); } } else { if (!CompilerSeparateur()) { if (*Source=='&') { Source++; Symbole * s=ChercherSymbole(); if (!EstNouveauSymbole(s) && s->EstClasse()) throw TXT("nom de troupeau innattendu après le symbole &"); else CompilerVariable(s, AVECET); } else if (!CompilerOperateur() && !CompilerSeparateur() && !CompilerTableau() && !CompilerConstante()) { if (*Source<=' ') throw CErreur(TXT("caractère 0x%x inattendu"),*Source); else throw CErreur(TXT("caractère %c inattendu"),*Source); } } else if (*Source==0) { if (AcFichierSource && AcFichierSource->Parent!=0) { AcFichierSource->FinCode=(code*)Ins.t; AcFichierSource=AcFichierSource->Parent; Ligne=AcFichierSource->Ligne; Source=AcFichierSource->AcPos; } else break; } } } Ins.AjouterCode(Code::I_STOP); if (AcSwitch.l) throw TXT("un GOTOMULTIPLE n'a pas été fermé"); // DebutLigne=Ins.c; //Bon on corrige tous les labels ! for (Symbole ** l=etaitPremierSymbole; l<programme->symbole.Fin(); l++) { if ((*l)->type==Symbole::FonctionGPP || (*l)->type==Symbole::MethodeGPP) { code * c=&Ins.c[(*l)->Valeur.v.i]; (*l)->Valeur.v.et=c; } } // qsort(&Label.Premier(),Label.l,sizeof(SLabel),CmpLabels); //clog << RefEtiq.l << " références à des étiquettes \n"; for (index_t z=0; z<RefEtiq.l; z++) { Symbole **k=(Symbole**)&Ins.c[RefEtiq[z]]; Symbole * v=*k; if (v->Valeur.Type!=TYPE_ETIQUETTE && v->Valeur.Type!=TYPE_ETIQUETTE_THIS ) throw CErreur(TXT("lors de l'édition des liens, l'étiquette %s%%%s n'a pas été définie"), v->parent->nom,v->nom); *((code**)k)=v->Valeur.v.et; } for (index_t z=0; z<RefEtiqL.l; z++) { Symbole **k=(Symbole **)&Ins.c[RefEtiqL[z]]; Symbole * v=*k; if (v->Valeur.Type!=TYPE_ETIQUETTE && v->Valeur.Type!=TYPE_ETIQUETTE_THIS ) throw CErreur(TXT("lors de l'édition des liens, l'étiquette %s n'a pas été définie"), v->nom); *((size_t*)k)=size_t((size_t)v->Valeur.v.et-(size_t)k-sizeof(size_t)); } //clog << "Taille du code : "<<Ins.t<<" octets\n"; if (blocs.l>1) throw TXT("tous les blocs d'instructions n'ont pas été fermés"); if (RefEtiqA.l) throw TXT("toutes les étiquettes automatiques n'ont pas été placées avec AC"); //On corrige tous les switchs for (index_t i=0; i<programme->Switch.l; i++) { for (index_t c=0; c<programme->Switch[i]->Cas.l; c++) programme->Switch[i]->Cas[c].Pos+=(size_t)Ins.c; if (programme->Switch[i]->PosDefaut) programme->Switch[i]->PosDefaut+=(size_t)Ins.c; } //On corrige tous les fichiers sources for (index_t i=EtaitPremierSource; i<programme->fichierSource.l; i++) { programme->fichierSource[i]->DebutCode+=(size_t)Ins.c; programme->fichierSource[i]->FinCode+=(size_t)Ins.c; } Ins.i=Ins.c; programme->InitVarGlob(); return Ins.CreerBoutCode(); } int Compilateur::AcLigne() { return Ligne; } carac * Compilateur::AcFichier() { if (AcFichierSource!=0) return AcFichierSource->Nom; else return TXT("<code dynamique>"); }
Sidoine/gotopp
src/compilateur/compilateur.cpp
C++
gpl-2.0
70,880
<?php if ( ! defined( 'ABSPATH' ) ) { die( '-1' ); } $events_label_singular = tribe_get_event_label_singular(); $events_label_plural = tribe_get_event_label_plural(); if ( ! $_POST ) { $event_cost = get_post_meta( $post_id, '_EventCost', false ); if (is_array($event_cost)) { if (empty($event_cost)) { $event_cost = ''; } else { $event_cost = $event_cost[0]; } } } else { $event_cost = isset( $_POST['EventCost'] ) ? esc_attr( $_POST['EventCost'] ) : ''; } if ( apply_filters( 'tribe_events_community_display_cost_section', true ) ) { ?> <div class="tribe_sectionheader"> <h4><?php tribe_community_events_field_label( 'EventCost', __( 'Cost', 'the-events-calendar') ); ?></h4> </div><!-- .tribe_sectionheader --> <div class="block"> <input type="checkbox" id="isFreeEventCheckbox" <?php checked($event_cost, '0'); ?> /> <label style="margin-right:20px;" for="isFreeEventCheckbox"><?php esc_html_e( 'Free', 'the-events-calendar' ); ?></label> <span id='EventCostContainer'> <label> <input type="text" id="EventCost" name="EventCost" size="10" value="<?php echo esc_attr( $event_cost ); ?>" /> рублей </label> </span> </div> <?php }//end if
Ilya-d/htdocs
wp-content/themes/malivi/templates/community/modules/cost.php
PHP
gpl-2.0
1,280
/* Warrior of Dreamworld, 2D Massivly Mutiplayer Online Role-playing Game Copyright (C) 2012 Ryan Lahfa This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "shared/Log.hpp" #include "ObjectMgr.hpp" #include <boost/archive/binary_iarchive.hpp> ObjectMgr* sObjectMgr; ObjectMgr::ObjectMgr(std::string const& TilesetPath, std::string const& TemplatesFilePath) : m_TilesetPath (TilesetPath), m_TemplatesFilePath (TemplatesFilePath) { } ObjectMgr::~ObjectMgr() { std::for_each(m_ItemTemplates.begin(), m_ItemTemplates.end(), MapDeleter()); std::for_each(m_CreatureTemplates.begin(), m_CreatureTemplates.end(), MapDeleter()); std::for_each(m_Tilesets.begin(), m_Tilesets.end(), MapDeleter()); std::for_each(m_Textures.begin(), m_Textures.end(), MapDeleter()); } void ObjectMgr::Initialize() { LoadTemplates(); } void ObjectMgr::LoadTileset(std::string const& FileName) { if (!SearchTileset(FileName)) { sf::Texture* tilesetTexture = new sf::Texture; if (!tilesetTexture->loadFromFile(m_TilesetPath + '/' + FileName)) { sLog.Write("Failed to load tileset texture: %s !", FileName); throw std::runtime_error("Failed to load a texture !"); } m_Tilesets[FileName] = tilesetTexture; } } ItemTemplate* ObjectMgr::GetItemTemplate(uint64 ItemID) { if (!SearchItemTemplate(ItemID)) { sLog.Write("Failed to find data about this item ID: %u !", ItemID); throw std::runtime_error("Failed to find data about something."); } return m_ItemTemplates[ItemID]; } sf::Texture* ObjectMgr::GetTileset(std::string const& TilesetName) { if (SearchTileset(TilesetName)) return m_Tilesets[TilesetName]; else { LoadTileset(TilesetName); return m_Tilesets[TilesetName]; } } sf::Texture* ObjectMgr::GetTileset(std::string const& TilesetName, sf::Color const& Mask, uint8 alpha) { if (SearchTileset(TilesetName)) return m_Tilesets[TilesetName]; else { LoadTileset(TilesetName); sf::Texture* tileset = m_Tilesets[TilesetName]; sf::Image imageTexture = tileset->copyToImage(); imageTexture.createMaskFromColor(Mask, alpha); tileset->update(imageTexture); return tileset; } } sf::Texture* ObjectMgr::GetTexture(std::string const& TextureName, std::string const& TexturePath) { auto TextureIt = m_Textures.find(TextureName); if (TextureIt != m_Textures.end()) return TextureIt->second; sf::Texture* Tex = new sf::Texture; if (!Tex->loadFromFile(TexturePath)) { sLog.Write("Failed to load texture (texture name: %s, texture path: %s)", TextureName, TexturePath); throw std::runtime_error("Failed to load texture."); } m_Textures[TextureName] = Tex; return Tex; } bool ObjectMgr::SearchItemTemplate(uint64 ItemID) const { return m_ItemTemplates.find(ItemID) != m_ItemTemplates.end(); } bool ObjectMgr::SearchCreatureTemplate(uint64 CreatureEntry) const { return m_CreatureTemplates.find(CreatureEntry) != m_CreatureTemplates.end(); } bool ObjectMgr::SearchTileset(std::string const& FileName) const { return m_Tilesets.find(FileName) != m_Tilesets.end(); } void ObjectMgr::LoadItemTemplate(std::string const& lineData) { ItemTemplate* Proto = new ItemTemplate; std::vector<std::string> data; boost::algorithm::split(data, lineData, boost::is_any_of(";"), boost::algorithm::token_compress_on); Proto->ItemID = boost::lexical_cast<uint64>(data.at(0)); Proto->Class = boost::lexical_cast<uint32>(data.at(1)); Proto->SubClass = boost::lexical_cast<uint32>(data.at(2)); Proto->Name = data.at(3); Proto->DisplayInfoID = boost::lexical_cast<uint32>(data.at(4)); Proto->InventoryType = boost::lexical_cast<uint8>(data.at(5)); Proto->Description = data.at(6); m_ItemTemplates[Proto->ItemID] = Proto; } void ObjectMgr::LoadCreatureTemplate(std::string const& lineData) { CreatureTemplate* Proto = new CreatureTemplate; std::vector<std::string> data; boost::algorithm::split(data, lineData, boost::is_any_of(";"), boost::algorithm::token_compress_on); Proto->Entry = boost::lexical_cast<uint64>(data.at(0)); Proto->Name = data.at(1); Proto->Tileset = data.at(2); Proto->tx = boost::lexical_cast<uint16>(data.at(3)); Proto->ty = boost::lexical_cast<uint16>(data.at(4)); Proto->npcflag = boost::lexical_cast<uint16>(data.at(5)); // Really needed by Client ? Proto->MaxHealth = boost::lexical_cast<uint32>(data.at(6)); Proto->MaxPower = boost::lexical_cast<uint32>(data.at(7)); m_CreatureTemplates[Proto->Entry] = Proto; } void ObjectMgr::LoadTemplates() { std::ifstream fileData(m_TemplatesFilePath); if (fileData) { std::string line; while (std::getline(fileData, line)) { int idxType = line.find(";"); std::string typeTemplate = line.substr(0, idxType); if (typeTemplate == "ItemTemplate") LoadItemTemplate(line.substr(idxType + 1)); else if (typeTemplate == "CreatureTemplate") LoadCreatureTemplate(line.substr(idxType + 1)); else if (typeTemplate == "QuestTemplate") // Skip it. Thanks to krofna! ; else sLog.Write("Unknown template type: %s. templates_info.dbc damaged ?", typeTemplate); } } else { sLog.Write("Failed to load templates data (FileName: %s)", m_TemplatesFilePath); throw std::runtime_error("Failed to load data."); } }
krofna/Warrior-of-Dreamworld
client/ObjectMgr.cpp
C++
gpl-2.0
6,332
/** * Copyright (C) 2002-2007 The FreeCol Team * * This file is part of FreeCol. * * FreeCol is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * FreeCol is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.common.model; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import net.sf.freecol.Reformation; import org.w3c.dom.Element; /** * Represents a work location on a tile. */ public class ColonyTile extends FreeColGameObject implements WorkLocation, Ownable { public static final String UNIT_CHANGE = "UNIT_CHANGE"; private Colony colony; private Tile workTile; private Unit unit; private boolean colonyCenterTile; /** * Creates a new <code>ColonyTile</code>. * * @param game The <code>Game</code> this object belongs to. * @param colony The <code>Colony</code> this object belongs to. * @param workTile The tile in which this <code>ColonyTile</code> represents a * <code>WorkLocation</code> for. */ public ColonyTile(Game game, Colony colony, Tile workTile) { super(game); this.colony = colony; this.workTile = workTile; if (colony.getTile() == workTile) { colonyCenterTile = true; } else { colonyCenterTile = false; } } /** * Initiates a new <code>Building</code> from an * XML representation. * * @param game The <code>Game</code> this object belongs to. * @param in The input stream containing the XML. * @throws XMLStreamException if an error occured during parsing. */ public ColonyTile(Game game, XMLStreamReader in) throws XMLStreamException { super(game, in); readFromXML(in); } /** * Initiates a new <code>Building</code> from an * XML representation. * * @param game The <code>Game</code> this object belongs to. * @param e An XML-element that will be used to initialize * this object. */ public ColonyTile(Game game, Element e) { super(game, e); readFromXMLElement(e); } /** * Initiates a new <code>ColonyTile</code> * with the given ID. The object should later be * initialized by calling either * {@link #readFromXML(XMLStreamReader)} or * {@link #readFromXMLElement(Element)}. * * @param game The <code>Game</code> in which this object belong. * @param id The unique identifier for this object. */ public ColonyTile(Game game, String id) { super(game, id); } /** * Gets the owner of this <code>Ownable</code>. * * @return The <code>Player</code> controlling this * {@link Ownable}. */ public Player getOwner() { return colony.getOwner(); } /** * Sets the owner of this <code>Ownable</code>. * * @param p The <code>Player</code> that should take ownership * of this {@link Ownable}. * @exception UnsupportedOperationException is always thrown by * this method. */ public void setOwner(Player p) { throw new UnsupportedOperationException(); } /** * Checks if this is the tile where the <code>Colony</code> is located. * @return The result. */ public boolean isColonyCenterTile() { return colonyCenterTile; } /** * Gets the work tile. * * @return The tile in which this <code>ColonyTile</code> represents a * <code>WorkLocation</code> for. */ public Tile getWorkTile() { return workTile; } /** * Gets the tile where the colony is located. * @return The <code>Tile</code>. */ public Tile getTile() { return colony.getTile(); } public GoodsContainer getGoodsContainer() { return null; } /** * Gets the <code>Unit</code> currently working on this <code>ColonyTile</code>. * * @return The <code>Unit</code> or <i>null</i> if no unit is present. * @see #setUnit */ public Unit getUnit() { return unit; } /** * Gets a pointer to the colony containing this tile. * @return The <code>Colony</code>. */ public Colony getColony() { return colony; } /** * Sets a <code>Unit</code> to this <code>ColonyTile</code>. * * @param unit The <code>Unit</code>. * @see #getUnit */ public void setUnit(Unit unit) { Unit oldUnit = getUnit(); this.unit = unit; if (oldUnit != null) { GoodsType workType = oldUnit.getWorkType(); firePropertyChange(workType.getId(), getProductionOf(oldUnit, workType), null); } if (unit != null) { GoodsType workType = unit.getWorkType(); // SOMEHOW, workType was null in unit tests if (workType != null) { firePropertyChange(workType.getId(), null, getProductionOf(unit, workType)); } } } /** * Gets the amount of Units at this <code>ColonyTile</code>. * @return The amount of Units at this <code>ColonyTile</code>. */ public int getUnitCount() { return (getUnit() != null) ? 1 : 0; } /** * Relocates any worker on this <code>ColonyTile</code>. * The workers are added to another {@link WorkLocation} * within the {@link Colony}. */ public void relocateWorkers() { if (getUnit() != null) { for (WorkLocation wl : getColony().getWorkLocations()) { if (wl != this && wl.canAdd(getUnit())) { getUnit().work(wl); break; } } } } /** * Check if this <code>WorkLocation</code> is available to the colony. * Used by canAdd() and the gui to decide whether to draw a border * on this tile in the colony panel. * * @return True if the location can be worked. */ public boolean canBeWorked() { Player player = getOwner(); // Not workable if there is a settlement, hostile occupation, // unable to work water, or lost city rumour to Europeans. Tile tile = getWorkTile(); if (tile.getSettlement() != null || tile.getOccupyingUnit() != null || !(tile.isLand() || colony.hasAbility("model.ability.produceInWater")) || (player.isEuropean() && tile.hasLostCityRumour())) { return false; } // Special cases when tile owned by another settlement. Settlement settlement = tile.getOwningSettlement(); if (settlement == null) { ; // OK } else if (settlement instanceof Colony) { // Disallow if owned by other Europeans or in active use. Colony otherColony = (Colony) settlement; if (otherColony != colony) { if (otherColony.getOwner() != player || otherColony.getColonyTile(tile).getUnit() != null) { return false; } } } else if (settlement instanceof IndianSettlement) { // Disallow if owned and valued by natives. if (player.getLandPrice(tile) > 0) { return false; } } else { throw new IllegalStateException("Bogus settlement"); } return true; } /** * Checks if the specified <code>Locatable</code> may be added to * this <code>WorkLocation</code>. * * @param locatable the <code>Locatable</code>. * @return <code>true</code> if the <code>Unit</code> may be added * and <code>false</code> otherwise. */ public boolean canAdd(Locatable locatable) { if (!canBeWorked()) { return false; } if (!(locatable instanceof Unit)) { return false; } Unit unit = (Unit) locatable; if (!unit.getType().hasSkill()) { return false; } return getUnit() == null || unit == getUnit(); } /** * Add the specified <code>Locatable</code> to this <code>WorkLocation</code>. * @param locatable The <code>Locatable</code> that shall be added to this <code>WorkLocation</code>. */ public void add(Locatable locatable) { if (isColonyCenterTile() || unit != null) { throw new IllegalStateException("Other unit present while adding a unit to ColonyTile:" + getId()); } if (!canAdd(locatable)) { if (getWorkTile().getOwningSettlement() != null && getWorkTile().getOwningSettlement() != getColony()) { throw new IllegalArgumentException("Cannot add locatable to this location: another colony claims this land!"); } throw new IllegalArgumentException("Cannot add locatable to this location: there is a unit here already!"); } Unit u = (Unit) locatable; u.removeAllEquipment(false); u.setState(Unit.UnitState.IN_COLONY); // Find a teacher if available. Unit potentialTeacher = getColony().findTeacher(u); if (potentialTeacher != null) { potentialTeacher.setStudent(u); u.setTeacher(potentialTeacher); } setUnit(u); } /** * Remove the specified <code>Locatable</code> from this <code>WorkLocation</code>. * @param locatable The <code>Locatable</code> that shall be removed from this <code>WorkLocation</code>. */ public void remove(Locatable locatable) { if (getUnit() == null) { return; } if (!getUnit().equals(locatable)) { return; } Unit oldUnit = getUnit(); oldUnit.setMovesLeft(0); setUnit(null); } public List<Unit> getUnitList() { if(getUnit() == null) { return new ArrayList<Unit>(); } else { return Collections.singletonList(getUnit()); } } public Iterator <Unit> getUnitIterator() { return getUnitList().iterator(); } /** * Checks if this <code>ColonyTile</code> contains the given <code>Locatable</code>. * * @param locatable The <code>Locatable</code>. * @return The result. */ public boolean contains(Locatable locatable) { return (locatable == unit) ? true:false; } /** * Gets the <code>Unit</code> currently working on this <code>ColonyTile</code>. * * @return The <code>Unit</code> or <i>null</i> if no unit is present. * @see #setUnit */ public Unit getFirstUnit() { return getUnit(); } /** * Gets the <code>Unit</code> currently working on this <code>ColonyTile</code>. * * @return The <code>Unit</code> or <i>null</i> if no unit is present. * @see #setUnit */ public Unit getLastUnit() { return getUnit(); } /** * Returns the unit who is occupying the tile * @return the unit who is occupying the tile * @see #isOccupied() */ public Unit getOccupyingUnit() { return workTile.getOccupyingUnit(); } /** * Checks whether there is a fortified enemy unit in the tile. * Units can't produce in occupied tiles * @return <code>true</code> if an fortified enemy unit is in the tile */ public boolean isOccupied() { return workTile.isOccupied(); } /** * Prepares this <code>ColonyTile</code> for a new turn. */ public void newTurn() { if (isColonyCenterTile()) { produceGoodsCenterTile(); } else if (getUnit() != null && !isOccupied()) { produceGoods(); workTile.expendResource(getUnit().getWorkType(), getUnit().getType(), colony); } } private void produceGoods() { int amount = getProductionOf(getUnit().getWorkType()); if (amount > 0) { colony.addGoods(getUnit().getWorkType(), amount); unit.modifyExperience(amount); } } private void produceGoodsCenterTile() { GoodsType goodsFood = workTile.primaryGoods(); colony.addGoods(goodsFood, getProductionOf(goodsFood)); GoodsType type2 = workTile.secondaryGoods(); if (type2 != null) colony.addGoods(type2, getProductionOf(type2)); } /** * Returns a worktype for a unit. * * @param unit a <code>Unit</code> value * @return a workType */ public GoodsType getWorkType(Unit unit) { GoodsType workType = unit.getWorkType(); int amount = getProductionOf(unit, workType); if (amount == 0) { List<GoodsType> farmedGoodsTypes = Reformation.getSpecification().getFarmedGoodsTypeList(); for(GoodsType farmedGoods : farmedGoodsTypes) { int newAmount = getProductionOf(unit, farmedGoods); if (newAmount > amount) { amount = newAmount; workType = farmedGoods; } } } return workType; } /** * Returns the production of the given type of goods. * * @param goodsType a <code>GoodsType</code> value * @return an <code>int</code> value */ public int getProductionOf(GoodsType goodsType) { if (goodsType == null) { throw new IllegalArgumentException("GoodsType must not be 'null'."); } else if (getUnit() == null) { if (isColonyCenterTile() && (goodsType.isFoodType() || goodsType.equals(workTile.secondaryGoods()))) { return workTile.potential(goodsType, null); } else { return 0; } } else if (goodsType.equals(getUnit().getWorkType())) { return getProductionOf(getUnit(), goodsType); } else { return 0; } } /** * Returns the production of the given type of goods. * * @param goodsType a <code>GoodsType</code> value * @param unitType a <code>unitType</code> value * @return an <code>int</code> value */ public Set<Modifier> getProductionModifiers(GoodsType goodsType, UnitType unitType) { if (goodsType == null) { throw new IllegalArgumentException("GoodsType must not be 'null'."); } else { Set<Modifier> result = new LinkedHashSet<Modifier>(); if (getUnit() == null) { if (isColonyCenterTile() && (goodsType.isFoodType() || goodsType.equals(workTile.secondaryGoods()))) { result.addAll(workTile.getProductionBonus(goodsType, null)); result.addAll(getColony().getFeatureContainer().getModifierSet(goodsType.getId())); } } else if (goodsType.equals(getUnit().getWorkType())) { result.addAll(workTile.getProductionBonus(goodsType, unitType)); result.addAll(getUnit().getModifierSet(goodsType.getId())); } return result; } } /** * Returns the production of the given type of goods which would * be produced by the given unit * * @param unit an <code>Unit</code> value * @param goodsType a <code>GoodsType</code> value * @return an <code>int</code> value */ public int getProductionOf(Unit unit, GoodsType goodsType) { if (unit == null) { throw new IllegalArgumentException("Unit must not be 'null'."); } else if (workTile.isLand() || colony.hasAbility("model.ability.produceInWater")) { int production = unit.getProductionOf(goodsType, workTile.potential(goodsType, unit.getType())); if (production > 0) { production = Math.max(1, production + colony.getProductionBonus()); } return production; } else { return 0; } } @Override public void dispose() { if (unit != null) { unit.dispose(); } super.dispose(); } /** * This method writes an XML-representation of this object to * the given stream. * * <br><br> * * Only attributes visible to the given <code>Player</code> will * be added to that representation if <code>showAll</code> is * set to <code>false</code>. * * @param out The target stream. * @param player The <code>Player</code> this XML-representation * should be made for, or <code>null</code> if * <code>showAll == true</code>. * @param showAll Only attributes visible to <code>player</code> * will be added to the representation if <code>showAll</code> * is set to <i>false</i>. * @param toSavedGame If <code>true</code> then information that * is only needed when saving a game is added. * @throws XMLStreamException if there are any problems writing * to the stream. */ @Override protected void toXMLImpl(XMLStreamWriter out, Player player, boolean showAll, boolean toSavedGame) throws XMLStreamException { // Start element: out.writeStartElement(getXMLElementTagName()); // Add attributes: out.writeAttribute("ID", getId()); out.writeAttribute("colony", colony.getId()); out.writeAttribute("workTile", workTile.getId()); writeFreeColGameObject(unit, out, player, showAll, toSavedGame); // End element: out.writeEndElement(); } /** * Initialize this object from an XML-representation of this object. * @param in The input stream with the XML. * @throws XMLStreamException if a problem was encountered * during parsing. */ @Override protected void readFromXMLImpl(XMLStreamReader in) throws XMLStreamException { setId(in.getAttributeValue(null, "ID")); colony = getFreeColGameObject(in, "colony", Colony.class); workTile = getFreeColGameObject(in, "workTile", Tile.class); colonyCenterTile = (colony.getTile() == workTile); unit = null; while (in.nextTag() != XMLStreamConstants.END_ELEMENT) { if (in.getLocalName().equals(Unit.getXMLElementTagName())) { setUnit(updateFreeColGameObject(in, Unit.class)); } } } /** * Will return the position of the tile and the name of the colony in * addition to the FreeColObject.toString(). * * @return A representation of a colony-tile that can be used for debugging. */ @Override public String toString() { return "ColonyTile " + getWorkTile().getPosition().toString() + " in '" + getColony().getName() + "'"; } /** * Gets the tag name of the root element representing this object. * @return "colonyTile". */ public static String getXMLElementTagName() { return "colonyTile"; } }
tectronics/reformationofeurope
src/net/sf/freecol/common/model/ColonyTile.java
Java
gpl-2.0
19,928
using System.Collections.Generic; using meridian.smolensk.proto; namespace smolensk.Models.ViewModels { public class AdsListViewModel { public string Title { get; set; } public string NoAdsTitle { get; set; } public IEnumerable<ad_advertisments> Advertisments { get; set; } public int TotalPages { get; set; } public int CurrentPage { get; set; } public bool IsFavorite { get; set; } public string RouteName { get; set; } public AdsListViewModel() { NoAdsTitle = "Нет объявлений"; } } }
seavan/smoltoday
trunk/src/smolensk/Models/ViewModels/AdsListViewModel.cs
C#
gpl-2.0
631
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using Sdl.Core.Settings; using SDLCommunityCleanUpTasks.Models; namespace SDLCommunityCleanUpTasks { public class CleanUpSourceSettings : SettingsGroup, ICleanUpSourceSettings { #region TagSettingsControl public Dictionary<string, bool> FormatTagList { get { return GetSetting<Dictionary<string, bool>>(nameof(FormatTagList)); } set { GetSetting<Dictionary<string, bool>>(nameof(FormatTagList)).Value = value; } } public Dictionary<string, bool> PlaceholderTagList { get { return GetSetting<Dictionary<string, bool>>(nameof(PlaceholderTagList)); } set { GetSetting<Dictionary<string, bool>>(nameof(PlaceholderTagList)).Value = value; } } public bool UseTagCleaner { get { return GetSetting<bool>(nameof(UseTagCleaner)); } set { GetSetting<bool>(nameof(UseTagCleaner)).Value = value; } } #endregion TagSettingsControl #region ConversionsSettingsControl public bool ApplyToNonTranslatables { get { return GetSetting<bool>(nameof(ApplyToNonTranslatables)); } set { GetSetting<bool>(nameof(ApplyToNonTranslatables)).Value = value; } } public Dictionary<string, bool> ConversionFiles { get { return GetSetting<Dictionary<string, bool>>(nameof(ConversionFiles)); } set { GetSetting<Dictionary<string, bool>>(nameof(ConversionFiles)).Value = value; } } public string LastFileDirectory { get { return GetSetting<string>(nameof(LastFileDirectory)); } set { GetSetting<string>(nameof(LastFileDirectory)).Value = value; } } public bool UseConversionSettings { get { return GetSetting<bool>(nameof(UseConversionSettings)); } set { GetSetting<bool>(nameof(UseConversionSettings)).Value = value; } } #endregion ConversionsSettingsControl #region SegmentLockerControl public BindingList<SegmentLockItem> SegmentLockList { get { return GetSetting<BindingList<SegmentLockItem>>(nameof(SegmentLockList)); } set { GetSetting<BindingList<SegmentLockItem>>(nameof(SegmentLockList)).Value = value; } } public List<ContextDef> StructureLockList { get { return GetSetting<List<ContextDef>>(nameof(StructureLockList)); } set { GetSetting<List<ContextDef>>(nameof(StructureLockList)).Value = value; } } public bool UseContentLocker { get { return GetSetting<bool>(nameof(UseContentLocker)); } set { GetSetting<bool>(nameof(UseContentLocker)).Value = value; } } public bool UseSegmentLocker { get { return GetSetting<bool>(nameof(UseSegmentLocker)); } set { GetSetting<bool>(nameof(UseSegmentLocker)).Value = value; } } public bool UseStructureLocker { get { return GetSetting<bool>(nameof(UseStructureLocker)); } set { GetSetting<bool>(nameof(UseStructureLocker)).Value = value; } } #endregion SegmentLockerControl public ISettingsGroup Settings { get; set; } public CultureInfo SourceCulture { get; set; } public List<Placeholder> Placeholders { get { return GetSetting<List<Placeholder>>(nameof(Placeholders)); } set { GetSetting<List<Placeholder>>(nameof(Placeholders)).Value = value; } } [SuppressMessage("Microsoft.Contracts", "TestAlwaysEvaluatingToAConstant")] protected override object GetDefaultValue(string settingId) { switch (settingId) { case nameof(UseTagCleaner): return true; case nameof(UseConversionSettings): return true; case nameof(ApplyToNonTranslatables): return false; case nameof(FormatTagList): return new Dictionary<string, bool>() { { TagTable.BackgroundColor, false }, { TagTable.Bold, false }, { TagTable.FontName, false }, { TagTable.FontSize, false }, { TagTable.TextColor, false }, { TagTable.Italic, false }, { TagTable.TextDirection, false }, { TagTable.TextPosition, false }, { TagTable.Underline, false }, { TagTable.Strikethrough, false } }; case nameof(PlaceholderTagList): return new Dictionary<string, bool>(); case nameof(ConversionFiles): return new Dictionary<string, bool>(); case nameof(LastFileDirectory): return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); case nameof(SegmentLockList): return new BindingList<SegmentLockItem>(new List<SegmentLockItem>()); case nameof(UseSegmentLocker): return true; case nameof(UseStructureLocker): return true; case nameof(UseContentLocker): return true; case nameof(StructureLockList): return new List<ContextDef>(); case nameof(Placeholders): return new List<Placeholder>(); } return base.GetDefaultValue(settingId); } } }
sdl/Sdl-Community
CleanUpTasks/CleanUpTasks/CleanUpSourceSettings.cs
C#
gpl-2.0
5,910
#! /usr/bin/python ###### # Copyright 2007-2009 Sun Microsystems, Inc. All Rights Reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER # # This code is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 # only, as published by the Free Software Foundation. # # This code is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License version 2 for more details (a copy is # included in the LICENSE file that accompanied this code). # # You should have received a copy of the GNU General Public License # version 2 along with this work; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA # # Please contact Sun Microsystems, Inc., 16 Network Circle, Menlo # Park, CA 94025 or visit www.sun.com if you need additional # information or have any questions. ##### import os import cPickle as C import pyaura.bridge as B from pyaura.lib import j2py DATA_PREFIX= "out500k" class SimpleStats(): """ Generate simple statistics and plots for a set of tags. """ def __init__(self, prefix=DATA_PREFIX, regHost="brannigan"): self.tags = C.load(open(os.path.join(prefix, "alltags.dump"))) self._dataFileCache = DataFileCache(prefix, self.tags) self._is_plot_init = False if regHost!=None: self._aB = B.AuraBridge(regHost=regHost) else: self._aB = None def _init_plotting(self, backend="MacOSX"): if not self._is_plot_init: self._is_plot_init = True import matplotlib as M M.use(backend) def plot_taglen_hist(self): self._init_plotting() import pylab tag_len = [len(x) for x in self.tags.keys() ] pylab.hist(tag_len) def plot_tagpop_itemcnt(self, itemtype="a"): """ Tag the histogram of the number of tagged items for each tag """ self._init_plotting() import pylab itemcnt = [x.get_itemcount(itemtype) for x in self.tags.values()] pylab.hist(itemcnt, bins=1000) def plot_tagpop_appcnt(self, itemtype="a"): """ Tag the histogram of application counts for each tag """ self._init_plotting() import pylab appcnt = [x.get_totals(itemtype) for x in self.tags.values()] pylab.hist(appcnt, bins=1000) def get_average_len(self): w_running_tot=0 running_tot=0 tot_cnt=0 nbr_cnt=0 for t in self.tags.values(): w_running_tot+=len(t.name)*t.totals['artist'] running_tot+=len(t.name) tot_cnt+=t.totals['artist'] nbr_cnt+=1 print "Weighted avg:\t%0.4f" % (float(w_running_tot)/tot_cnt) print "Avg:\t\t%0.4f" % (float(running_tot)/nbr_cnt) def find_most_co_ocurr(self, tagname, n=10): vals = {} for t in self.tags: vals[t] = self.co_ocurr(tagname, t) return sorted(vals.items(), key=lambda (k,v): (v,k), reverse=True) def find_similar(self, tagname, n=10): return j2py( self._aB.mdb.find_similar_rawtags(tagname, n) ) def co_ocurr(self, tagname1, tagname2): """ Get relative co-occurence (Jaccard coefficient) """ tagdata1 = self._dataFileCache.get(tagname1) tagdata2 = self._dataFileCache.get(tagname2) kt1 = frozenset(tagdata1['artist'].keys()) kt2 = frozenset(tagdata2['artist'].keys()) return float(len(kt1.intersection(kt2))) / len(kt1.union(kt2)) class DataFileCache(): def __init__(self, prefix, taginfo): self._prefix = prefix self._taginfo = taginfo self._datafiles = {} def get(self, tagname): if tagname not in self._taginfo: raise KeyError("Tag '%s' is not in the db" % tagname) file_id = self._taginfo[tagname].file_location if not file_id in self._datafiles: print " > Loading datafile %s" % file_id path = os.path.join(self._prefix, "tagcut-%s.tagdata.dump" % file_id) self._datafiles[file_id] = C.load(open(path)) return self._datafiles[file_id][tagname]
SunLabsAST/AURA
Bridge/pyaura/tagclustering/simplestats.py
Python
gpl-2.0
4,439
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.internal.policy.impl.keyguard; import android.app.PendingIntent; import android.app.PendingIntent.CanceledException; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.media.AudioManager; import android.media.IRemoteControlDisplay; import android.media.MediaMetadataRetriever; import android.media.RemoteControlClient; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Parcel; import android.os.Parcelable; import android.os.RemoteException; import android.os.SystemClock; import android.text.Spannable; import android.text.TextUtils; import android.text.style.ForegroundColorSpan; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.android.internal.R; import java.lang.ref.WeakReference; /** * This is the widget responsible for showing music controls in keyguard. */ public class KeyguardTransportControlView extends FrameLayout implements OnClickListener { private static final int MSG_UPDATE_STATE = 100; private static final int MSG_SET_METADATA = 101; private static final int MSG_SET_TRANSPORT_CONTROLS = 102; private static final int MSG_SET_ARTWORK = 103; private static final int MSG_SET_GENERATION_ID = 104; private static final int DISPLAY_TIMEOUT_MS = 5000; // 5s protected static final boolean DEBUG = false; protected static final String TAG = "TransportControlView"; private ImageView mAlbumArt; private TextView mTrackTitle; private ImageView mBtnPrev; private ImageView mBtnPlay; private ImageView mBtnNext; private int mClientGeneration; private Metadata mMetadata = new Metadata(); private boolean mAttached; private PendingIntent mClientIntent; private int mTransportControlFlags; private int mCurrentPlayState; private AudioManager mAudioManager; private IRemoteControlDisplayWeak mIRCD; private boolean mMusicClientPresent = true; /** * The metadata which should be populated into the view once we've been attached */ private Bundle mPopulateMetadataWhenAttached = null; // This handler is required to ensure messages from IRCD are handled in sequence and on // the UI thread. private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_UPDATE_STATE: if (mClientGeneration == msg.arg1) updatePlayPauseState(msg.arg2); break; case MSG_SET_METADATA: if (mClientGeneration == msg.arg1) updateMetadata((Bundle) msg.obj); break; case MSG_SET_TRANSPORT_CONTROLS: if (mClientGeneration == msg.arg1) updateTransportControls(msg.arg2); break; case MSG_SET_ARTWORK: if (mClientGeneration == msg.arg1) { if (mMetadata.bitmap != null) { mMetadata.bitmap.recycle(); } mMetadata.bitmap = (Bitmap) msg.obj; mAlbumArt.setImageBitmap(mMetadata.bitmap); } break; case MSG_SET_GENERATION_ID: if (msg.arg2 != 0) { // This means nobody is currently registered. Hide the view. onListenerDetached(); } else { onListenerAttached(); } if (DEBUG) Log.v(TAG, "New genId = " + msg.arg1 + ", clearing = " + msg.arg2); mClientGeneration = msg.arg1; mClientIntent = (PendingIntent) msg.obj; break; } } }; private KeyguardHostView.TransportCallback mTransportCallback; /** * This class is required to have weak linkage to the current TransportControlView * because the remote process can hold a strong reference to this binder object and * we can't predict when it will be GC'd in the remote process. Without this code, it * would allow a heavyweight object to be held on this side of the binder when there's * no requirement to run a GC on the other side. */ private static class IRemoteControlDisplayWeak extends IRemoteControlDisplay.Stub { private WeakReference<Handler> mLocalHandler; IRemoteControlDisplayWeak(Handler handler) { mLocalHandler = new WeakReference<Handler>(handler); } public void setPlaybackState(int generationId, int state, long stateChangeTimeMs) { Handler handler = mLocalHandler.get(); if (handler != null) { handler.obtainMessage(MSG_UPDATE_STATE, generationId, state).sendToTarget(); } } public void setMetadata(int generationId, Bundle metadata) { Handler handler = mLocalHandler.get(); if (handler != null) { handler.obtainMessage(MSG_SET_METADATA, generationId, 0, metadata).sendToTarget(); } } public void setTransportControlFlags(int generationId, int flags) { Handler handler = mLocalHandler.get(); if (handler != null) { handler.obtainMessage(MSG_SET_TRANSPORT_CONTROLS, generationId, flags) .sendToTarget(); } } public void setArtwork(int generationId, Bitmap bitmap) { Handler handler = mLocalHandler.get(); if (handler != null) { handler.obtainMessage(MSG_SET_ARTWORK, generationId, 0, bitmap).sendToTarget(); } } public void setAllMetadata(int generationId, Bundle metadata, Bitmap bitmap) { Handler handler = mLocalHandler.get(); if (handler != null) { handler.obtainMessage(MSG_SET_METADATA, generationId, 0, metadata).sendToTarget(); handler.obtainMessage(MSG_SET_ARTWORK, generationId, 0, bitmap).sendToTarget(); } } public void setCurrentClientId(int clientGeneration, PendingIntent mediaIntent, boolean clearing) throws RemoteException { Handler handler = mLocalHandler.get(); if (handler != null) { handler.obtainMessage(MSG_SET_GENERATION_ID, clientGeneration, (clearing ? 1 : 0), mediaIntent).sendToTarget(); } } }; public KeyguardTransportControlView(Context context, AttributeSet attrs) { super(context, attrs); if (DEBUG) Log.v(TAG, "Create TCV " + this); mAudioManager = new AudioManager(mContext); mCurrentPlayState = RemoteControlClient.PLAYSTATE_NONE; // until we get a callback mIRCD = new IRemoteControlDisplayWeak(mHandler); } protected void onListenerDetached() { mMusicClientPresent = false; if (DEBUG) Log.v(TAG, "onListenerDetached()"); if (mTransportCallback != null) { mTransportCallback.onListenerDetached(); } else { Log.w(TAG, "onListenerDetached: no callback"); } } private void onListenerAttached() { mMusicClientPresent = true; if (DEBUG) Log.v(TAG, "onListenerAttached()"); if (mTransportCallback != null) { mTransportCallback.onListenerAttached(); } else { Log.w(TAG, "onListenerAttached(): no callback"); } } private void updateTransportControls(int transportControlFlags) { mTransportControlFlags = transportControlFlags; } @Override public void onFinishInflate() { super.onFinishInflate(); mTrackTitle = (TextView) findViewById(R.id.title); mTrackTitle.setSelected(true); // enable marquee mAlbumArt = (ImageView) findViewById(R.id.albumart); mBtnPrev = (ImageView) findViewById(R.id.btn_prev); mBtnPlay = (ImageView) findViewById(R.id.btn_play); mBtnNext = (ImageView) findViewById(R.id.btn_next); final View buttons[] = { mBtnPrev, mBtnPlay, mBtnNext }; for (View view : buttons) { view.setOnClickListener(this); } } @Override public void onAttachedToWindow() { super.onAttachedToWindow(); if (DEBUG) Log.v(TAG, "onAttachToWindow()"); if (mPopulateMetadataWhenAttached != null) { updateMetadata(mPopulateMetadataWhenAttached); mPopulateMetadataWhenAttached = null; } if (!mAttached) { if (DEBUG) Log.v(TAG, "Registering TCV " + this); mAudioManager.registerRemoteControlDisplay(mIRCD); } mAttached = true; } @Override public void onDetachedFromWindow() { if (DEBUG) Log.v(TAG, "onDetachFromWindow()"); super.onDetachedFromWindow(); if (mAttached) { if (DEBUG) Log.v(TAG, "Unregistering TCV " + this); mAudioManager.unregisterRemoteControlDisplay(mIRCD); } mAttached = false; } class Metadata { private String artist; private String trackTitle; private String albumTitle; private Bitmap bitmap; public String toString() { return "Metadata[artist=" + artist + " trackTitle=" + trackTitle + " albumTitle=" + albumTitle + "]"; } } private String getMdString(Bundle data, int id) { return data.getString(Integer.toString(id)); } private void updateMetadata(Bundle data) { if (mAttached) { mMetadata.artist = getMdString(data, MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST); mMetadata.trackTitle = getMdString(data, MediaMetadataRetriever.METADATA_KEY_TITLE); mMetadata.albumTitle = getMdString(data, MediaMetadataRetriever.METADATA_KEY_ALBUM); populateMetadata(); } else { mPopulateMetadataWhenAttached = data; } } /** * Populates the given metadata into the view */ private void populateMetadata() { StringBuilder sb = new StringBuilder(); int trackTitleLength = 0; if (!TextUtils.isEmpty(mMetadata.trackTitle)) { sb.append(mMetadata.trackTitle); trackTitleLength = mMetadata.trackTitle.length(); } if (!TextUtils.isEmpty(mMetadata.artist)) { if (sb.length() != 0) { sb.append(" - "); } sb.append(mMetadata.artist); } if (!TextUtils.isEmpty(mMetadata.albumTitle)) { if (sb.length() != 0) { sb.append(" - "); } sb.append(mMetadata.albumTitle); } mTrackTitle.setText(sb.toString(), TextView.BufferType.SPANNABLE); Spannable str = (Spannable) mTrackTitle.getText(); if (trackTitleLength != 0) { str.setSpan(new ForegroundColorSpan(0xffffffff), 0, trackTitleLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); trackTitleLength++; } if (sb.length() > trackTitleLength) { str.setSpan(new ForegroundColorSpan(0x7fffffff), trackTitleLength, sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } mAlbumArt.setImageBitmap(mMetadata.bitmap); final int flags = mTransportControlFlags; setVisibilityBasedOnFlag(mBtnPrev, flags, RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS); setVisibilityBasedOnFlag(mBtnNext, flags, RemoteControlClient.FLAG_KEY_MEDIA_NEXT); setVisibilityBasedOnFlag(mBtnPlay, flags, RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_STOP); updatePlayPauseState(mCurrentPlayState); } public boolean isMusicPlaying() { return mCurrentPlayState == RemoteControlClient.PLAYSTATE_PLAYING || mCurrentPlayState == RemoteControlClient.PLAYSTATE_BUFFERING; } private static void setVisibilityBasedOnFlag(View view, int flags, int flag) { if ((flags & flag) != 0) { view.setVisibility(View.VISIBLE); } else { view.setVisibility(View.GONE); } } private void updatePlayPauseState(int state) { if (DEBUG) Log.v(TAG, "updatePlayPauseState(), old=" + mCurrentPlayState + ", state=" + state); if (state == mCurrentPlayState) { return; } final int imageResId; final int imageDescId; switch (state) { case RemoteControlClient.PLAYSTATE_ERROR: imageResId = com.android.internal.R.drawable.stat_sys_warning; // TODO use more specific image description string for warning, but here the "play" // message is still valid because this button triggers a play command. imageDescId = com.android.internal.R.string.lockscreen_transport_play_description; break; case RemoteControlClient.PLAYSTATE_PLAYING: imageResId = com.android.internal.R.drawable.ic_media_pause; imageDescId = com.android.internal.R.string.lockscreen_transport_pause_description; break; case RemoteControlClient.PLAYSTATE_BUFFERING: imageResId = com.android.internal.R.drawable.ic_media_stop; imageDescId = com.android.internal.R.string.lockscreen_transport_stop_description; break; case RemoteControlClient.PLAYSTATE_PAUSED: default: imageResId = com.android.internal.R.drawable.ic_media_play; imageDescId = com.android.internal.R.string.lockscreen_transport_play_description; break; } mBtnPlay.setImageResource(imageResId); mBtnPlay.setContentDescription(getResources().getString(imageDescId)); mCurrentPlayState = state; mTransportCallback.onPlayStateChanged(); } static class SavedState extends BaseSavedState { boolean clientPresent; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); this.clientPresent = in.readInt() != 0; } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(this.clientPresent ? 1 : 0); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.clientPresent = mMusicClientPresent; return ss; } @Override public void onRestoreInstanceState(Parcelable state) { if (!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return; } SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); if (ss.clientPresent) { if (DEBUG) Log.v(TAG, "Reattaching client because it was attached"); onListenerAttached(); } } public void onClick(View v) { int keyCode = -1; if (v == mBtnPrev) { keyCode = KeyEvent.KEYCODE_MEDIA_PREVIOUS; } else if (v == mBtnNext) { keyCode = KeyEvent.KEYCODE_MEDIA_NEXT; } else if (v == mBtnPlay) { keyCode = KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE; } if (keyCode != -1) { sendMediaButtonClick(keyCode); } } private void sendMediaButtonClick(int keyCode) { if (mClientIntent == null) { // Shouldn't be possible because this view should be hidden in this case. Log.e(TAG, "sendMediaButtonClick(): No client is currently registered"); return; } // use the registered PendingIntent that will be processed by the registered // media button event receiver, which is the component of mClientIntent KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode); Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON); intent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent); try { mClientIntent.send(getContext(), 0, intent); } catch (CanceledException e) { Log.e(TAG, "Error sending intent for media button down: "+e); e.printStackTrace(); } keyEvent = new KeyEvent(KeyEvent.ACTION_UP, keyCode); intent = new Intent(Intent.ACTION_MEDIA_BUTTON); intent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent); try { mClientIntent.send(getContext(), 0, intent); } catch (CanceledException e) { Log.e(TAG, "Error sending intent for media button up: "+e); e.printStackTrace(); } } public boolean providesClock() { return false; } private boolean wasPlayingRecently(int state, long stateChangeTimeMs) { switch (state) { case RemoteControlClient.PLAYSTATE_PLAYING: case RemoteControlClient.PLAYSTATE_FAST_FORWARDING: case RemoteControlClient.PLAYSTATE_REWINDING: case RemoteControlClient.PLAYSTATE_SKIPPING_FORWARDS: case RemoteControlClient.PLAYSTATE_SKIPPING_BACKWARDS: case RemoteControlClient.PLAYSTATE_BUFFERING: // actively playing or about to play return true; case RemoteControlClient.PLAYSTATE_NONE: return false; case RemoteControlClient.PLAYSTATE_STOPPED: case RemoteControlClient.PLAYSTATE_PAUSED: case RemoteControlClient.PLAYSTATE_ERROR: // we have stopped playing, check how long ago if (DEBUG) { if ((SystemClock.elapsedRealtime() - stateChangeTimeMs) < DISPLAY_TIMEOUT_MS) { Log.v(TAG, "wasPlayingRecently: time < TIMEOUT was playing recently"); } else { Log.v(TAG, "wasPlayingRecently: time > TIMEOUT"); } } return ((SystemClock.elapsedRealtime() - stateChangeTimeMs) < DISPLAY_TIMEOUT_MS); default: Log.e(TAG, "Unknown playback state " + state + " in wasPlayingRecently()"); return false; } } public void setKeyguardCallback(KeyguardHostView.TransportCallback transportCallback) { mTransportCallback = transportCallback; } }
rex-xxx/mt6572_x201
frameworks/base/policy/src/com/android/internal/policy/impl/keyguard/KeyguardTransportControlView.java
Java
gpl-2.0
19,994
/* * Wazuh app - Mitre alerts components * Copyright (C) 2015-2021 Wazuh, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Find more information about this on the LICENSE file. */ import React, { Component } from 'react' import { EuiPanel, EuiFlexGroup, EuiFlexItem, } from '@elastic/eui'; import { SearchBar, FilterManager } from '../../../../../../src/plugins/data/public/'; import { I18nProvider } from '@kbn/i18n/react'; //@ts-ignore import { ComplianceRequirements } from './components/requirements'; import { ComplianceSubrequirements } from './components/subrequirements'; import { getElasticAlerts, getIndexPattern, IFilterParams } from '../mitre/lib'; import { pciRequirementsFile } from '../../../../common/compliance-requirements/pci-requirements'; import { gdprRequirementsFile } from '../../../../common/compliance-requirements/gdpr-requirements'; import { hipaaRequirementsFile } from '../../../../common/compliance-requirements/hipaa-requirements'; import { nistRequirementsFile } from '../../../../common/compliance-requirements/nist-requirements'; import { tscRequirementsFile } from '../../../../common/compliance-requirements/tsc-requirements'; import { KbnSearchBar } from '../../kbn-search-bar'; import { getDataPlugin } from '../../../kibana-services'; export class ComplianceTable extends Component { _isMount = false; timefilter: { getTime(): any setTime(time: any): void _history: { history: { items: { from: string, to: string }[] } } }; KibanaServices: { [key: string]: any }; filterManager: FilterManager; indexPattern: any; state: { selectedRequirement: string, flyoutOn: boolean, filterParams: IFilterParams, complianceObject: object, descriptions: object, loadingAlerts: boolean selectedRequirements: object, } props: any; constructor(props) { super(props); this.KibanaServices = getDataPlugin().query; this.filterManager = this.KibanaServices.filterManager; this.timefilter = this.KibanaServices.timefilter.timefilter; this.state = { selectedRequirement: "", flyoutOn: true, complianceObject: {}, descriptions: {}, loadingAlerts: true, selectedRequirements: {}, filterParams: { filters: this.filterManager.getFilters() || [], query: { language: 'kuery', query: '' }, time: this.timefilter.getTime(), }, } this.onChangeSelectedRequirements.bind(this); this.onQuerySubmit.bind(this); this.onFiltersUpdated.bind(this); } async componentDidMount() { this._isMount = true; this.filtersSubscriber = this.filterManager.getUpdates$().subscribe(() => { this.onFiltersUpdated(this.filterManager.getFilters()) }); this.indexPattern = await getIndexPattern(); this.buildComplianceObject(); } componentWillUnmount() { this.filtersSubscriber.unsubscribe(); } buildComplianceObject() { try { let complianceRequirements = {}; let descriptions = {}; let selectedRequirements = {}; // all enabled by default if (this.props.section === 'pci') { descriptions = pciRequirementsFile; Object.keys(pciRequirementsFile).forEach(item => { const currentRequirement = item.split(".")[0]; if (complianceRequirements[currentRequirement]) { complianceRequirements[currentRequirement].push(item); } else { selectedRequirements[currentRequirement] = true; complianceRequirements[currentRequirement] = []; complianceRequirements[currentRequirement].push(item); } }); //forEach } if (this.props.section === 'gdpr') { descriptions = gdprRequirementsFile; Object.keys(gdprRequirementsFile).forEach(item => { const currentRequirement = item.split("_")[0]; if (complianceRequirements[currentRequirement]) { complianceRequirements[currentRequirement].push(item); } else { selectedRequirements[currentRequirement] = true; complianceRequirements[currentRequirement] = []; complianceRequirements[currentRequirement].push(item); } }); //forEach } if (this.props.section === 'hipaa') { descriptions = hipaaRequirementsFile; Object.keys(hipaaRequirementsFile).forEach(item => { const currentRequirement = item.split(".")[0] + "." + item.split(".")[1] + "." + item.split(".")[2]; if (complianceRequirements[currentRequirement]) { complianceRequirements[currentRequirement].push(item); } else { selectedRequirements[currentRequirement] = true; complianceRequirements[currentRequirement] = []; complianceRequirements[currentRequirement].push(item); } }); //forEach } if (this.props.section === 'nist') { descriptions = nistRequirementsFile; Object.keys(nistRequirementsFile).forEach(item => { const currentRequirement = item.split(".")[0]; if (complianceRequirements[currentRequirement]) { complianceRequirements[currentRequirement].push(item); } else { selectedRequirements[currentRequirement] = true; complianceRequirements[currentRequirement] = []; complianceRequirements[currentRequirement].push(item); } }); //forEach } if (this.props.section === 'tsc') { descriptions = tscRequirementsFile; Object.keys(tscRequirementsFile).forEach(item => { const currentRequirement = item.split(".")[0]; if (complianceRequirements[currentRequirement]) { complianceRequirements[currentRequirement].push(item); } else { selectedRequirements[currentRequirement] = true; complianceRequirements[currentRequirement] = []; complianceRequirements[currentRequirement].push(item); } }); //forEach } this._isMount && this.setState({ complianceObject: complianceRequirements, selectedRequirements, descriptions }, () => this.getRequirementsCount()); } catch (err) { // TODO ADD showToast /*this.showToast( 'danger', 'Error', `Compliance (${this.props.section}) data could not be fetched: ${err}`, 3000 );*/ } } onChangeSelectedRequirements = (selectedRequirements) => { this.setState({ selectedRequirements }); } onQuerySubmit = (payload: { dateRange: TimeRange, query: Query | undefined }) => { const { dateRange, query } = payload; const { filters } = this.state.filterParams; const filterParams:IFilterParams = { time: dateRange, filters, query}; this.setState({ filterParams, loadingAlerts: true }); } onFiltersUpdated = (filters: []) => { const { time, query} = this.state.filterParams; const filterParams = {time, query, filters}; this.setState({ filterParams, loadingAlerts: true }); } async componentDidUpdate(prevProps) { const { filterParams, loadingAlerts } = this.state; if (JSON.stringify(prevProps.filterParams) !== JSON.stringify(filterParams) && loadingAlerts) { this.getRequirementsCount(); } } async getRequirementsCount() { try { const { filterParams } = this.state; if (!this.indexPattern) { return; } let fieldAgg = ""; if (this.props.section === "pci") fieldAgg = "rule.pci_dss"; if (this.props.section === "gdpr") fieldAgg = "rule.gdpr"; if (this.props.section === "hipaa") fieldAgg = "rule.hipaa"; if (this.props.section === "nist") fieldAgg = "rule.nist_800_53"; if (this.props.section === "tsc") fieldAgg = "rule.tsc"; const aggs = { tactics: { terms: { field: fieldAgg, size: 100, } } } // TODO: use `status` and `statusText` to show errors // @ts-ignore const { data, status, statusText, } = await getElasticAlerts(this.indexPattern, filterParams, aggs); const { buckets } = data.aggregations.tactics; /*if(firstTime){ this.initTactics(buckets); // top tactics are checked on component mount }*/ this._isMount && this.setState({ requirementsCount: buckets, loadingAlerts: false, firstTime: false }); } catch (err) { /* this.showToast( 'danger', 'Error', `Mitre alerts could not be fetched: ${err}`, 3000 );*/ this.setState({ loadingAlerts: false }) } } onChangeFlyout = (flyoutOn) => { this.setState({ flyoutOn }); } closeFlyout() { this.setState({ flyoutOn: false }); } showFlyout(requirement) { this.setState({ selectedRequirement: requirement, flyoutOn: true }) } render() { const { complianceObject, loadingAlerts } = this.state; return (<div> <EuiFlexGroup> <EuiFlexItem> <div className='wz-discover hide-filter-control' > <KbnSearchBar onQuerySubmit={this.onQuerySubmit} onFiltersUpdated={this.onFiltersUpdated} isLoading={loadingAlerts} /> </div> </EuiFlexItem> </EuiFlexGroup> <EuiFlexGroup style={{ margin: '0 8px' }}> <EuiFlexItem style={{ width: "calc(100% - 24px)" }}> <EuiPanel paddingSize="none"> {!!Object.keys(complianceObject).length && this.state.filterParams.time.from !== "init" && <EuiFlexGroup> <EuiFlexItem grow={false} style={{ width: "15%", minWidth: 145, maxHeight: "calc(100vh - 320px)", overflowX: "hidden" }}> <ComplianceRequirements indexPattern={this.indexPattern} section={this.props.section} onChangeSelectedRequirements={this.onChangeSelectedRequirements} {...this.state} /> </EuiFlexItem> <EuiFlexItem style={{ width: "15%" }}> <ComplianceSubrequirements indexPattern={this.indexPattern} filters={this.state.filterParams} section={this.props.section} onSelectedTabChanged={(id) => this.props.onSelectedTabChanged(id)} {...this.state} /> </EuiFlexItem> </EuiFlexGroup> } </EuiPanel> </EuiFlexItem> </EuiFlexGroup> </div> ) } }
wazuh/wazuh-kibana-app
public/components/overview/compliance-table/compliance-table.tsx
TypeScript
gpl-2.0
10,864
package org.kidneyomics.gtf; import static org.junit.Assert.*; import java.util.LinkedList; import java.util.List; import org.biojava.nbio.genome.parsers.gff.Feature; import org.biojava.nbio.genome.parsers.gff.Location; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FeatureMergerTest { Logger logger = LoggerFactory.getLogger(FeatureMergerTest.class); @Test public void test() { Feature f1 = new Feature("chr1", "a", "exon", Location.fromBio(100, 200, '+'), 0.0, 0, ""); Feature f2 = new Feature("chr1", "a", "exon", Location.fromBio(50, 150, '+'), 0.0, 0, ""); Feature f3 = new Feature("chr1", "a", "exon", Location.fromBio(250, 300, '+'), 0.0, 0, ""); List<Feature> features = new LinkedList<Feature>(); features.add(f1); features.add(f2); features.add(f3); List<Feature> merged = FeatureMerger.mergeOverlappingFeatures(features); assertTrue(merged.size() == 2); Feature m1 = merged.get(0); assertEquals(50, m1.location().bioStart()); assertEquals(200, m1.location().bioEnd()); Feature m2 = merged.get(1); assertEquals(250, m2.location().bioStart()); assertEquals(300, m2.location().bioEnd()); } @Test public void test2() { Feature f1 = new Feature("chr1", "a", "exon", Location.fromBio(100, 200, '+'), 0.0, 0, ""); Feature f2 = new Feature("chr1", "a", "exon", Location.fromBio(50, 150, '-'), 0.0, 0, ""); Feature f3 = new Feature("chr1", "a", "exon", Location.fromBio(250, 300, '+'), 0.0, 0, ""); List<Feature> features = new LinkedList<Feature>(); features.add(f1); features.add(f2); features.add(f3); List<Feature> merged = FeatureMerger.mergeOverlappingFeaturesIgnoringStrand(features); assertTrue(merged.size() == 2); Feature m1 = merged.get(0); assertEquals(50, m1.location().bioStart()); assertEquals(200, m1.location().bioEnd()); Feature m2 = merged.get(1); assertEquals(250, m2.location().bioStart()); assertEquals(300, m2.location().bioEnd()); } @Test public void test3() { Feature f1 = new Feature("chr1", "a", "exon", Location.fromBio(100, 200, '+'), 0.0, 0, ""); Feature f2 = new Feature("chr1", "a", "exon", Location.fromBio(50, 150, '-'), 0.0, 0, ""); Feature f3 = new Feature("chr1", "a", "exon", Location.fromBio(250, 300, '+'), 0.0, 0, ""); List<Feature> features = new LinkedList<Feature>(); features.add(f1); features.add(f2); features.add(f3); IllegalArgumentException exception = null; try { FeatureMerger.mergeOverlappingFeatures(features); } catch(IllegalArgumentException e) { exception = e; } assertNotNull(exception); } @Test public void test4() { Feature f1 = new Feature("chr1", "a", "exon", Location.fromBio(1, 400, '+'), 0.0, 0, ""); Feature f2 = new Feature("chr1", "a", "exon", Location.fromBio(50, 150, '-'), 0.0, 0, ""); Feature f3 = new Feature("chr1", "a", "exon", Location.fromBio(250, 300, '+'), 0.0, 0, ""); List<Feature> features = new LinkedList<Feature>(); features.add(f1); features.add(f2); features.add(f3); List<Feature> merged = FeatureMerger.mergeOverlappingFeaturesIgnoringStrand(features); assertTrue(merged.size() == 1); Feature m1 = merged.get(0); assertEquals(1, m1.location().bioStart()); assertEquals(400, m1.location().bioEnd()); } @Test public void testRemoveOverlappingFeatures() { Feature f0 = new Feature("chr1", "a", "exon", Location.fromBio(50, 99, '+'), 0.0, 0, ""); Feature f1 = new Feature("chr1", "a", "exon", Location.fromBio(100, 200, '+'), 0.0, 0, ""); Feature f2 = new Feature("chr1", "a", "exon", Location.fromBio(150, 250, '+'), 0.0, 0, ""); Feature f3 = new Feature("chr1", "a", "exon", Location.fromBio(260, 300, '+'), 0.0, 0, ""); List<Feature> features = new LinkedList<Feature>(); features.add(f0); features.add(f1); features.add(f2); features.add(f3); List<Feature> removed = FeatureMerger.removeOverlappingFeaturesIgnoreStrand(features); logger.info("removed"); for(Feature f : removed) { logger.info(GTFFeatureRenderer.render(f)); } logger.info("kept"); for(Feature f : features) { logger.info(GTFFeatureRenderer.render(f)); } assertEquals(2,removed.size()); assertEquals(2,features.size()); assertEquals(100,removed.get(0).location().bioStart()); assertEquals(200,removed.get(0).location().bioEnd()); assertEquals(150,removed.get(1).location().bioStart()); assertEquals(250,removed.get(1).location().bioEnd()); assertEquals(50,features.get(0).location().bioStart()); assertEquals(99,features.get(0).location().bioEnd()); assertEquals(260,features.get(1).location().bioStart()); assertEquals(300,features.get(1).location().bioEnd()); } @Test public void testRemoveOverlappingFeatures2() { Feature f0 = new Feature("chr1", "a", "exon", Location.fromBio(1, 261, '+'), 0.0, 0, ""); Feature f1 = new Feature("chr1", "a", "exon", Location.fromBio(100, 200, '+'), 0.0, 0, ""); Feature f2 = new Feature("chr1", "a", "exon", Location.fromBio(150, 250, '+'), 0.0, 0, ""); Feature f3 = new Feature("chr1", "a", "exon", Location.fromBio(260, 300, '+'), 0.0, 0, ""); List<Feature> features = new LinkedList<Feature>(); features.add(f0); features.add(f1); features.add(f2); features.add(f3); List<Feature> removed = FeatureMerger.removeOverlappingFeaturesIgnoreStrand(features); assertEquals(4,removed.size()); assertEquals(0,features.size()); assertEquals(100,removed.get(0).location().bioStart()); assertEquals(200,removed.get(0).location().bioEnd()); assertEquals(150,removed.get(1).location().bioStart()); assertEquals(250,removed.get(1).location().bioEnd()); assertEquals(1,removed.get(2).location().bioStart()); assertEquals(261,removed.get(2).location().bioEnd()); assertEquals(260,removed.get(3).location().bioStart()); assertEquals(300,removed.get(3).location().bioEnd()); } @Test public void testRemoveOverlappingFeatures3() { Feature f0 = new Feature("chr1", "a", "exon", Location.fromBio(1, 50, '+'), 0.0, 0, ""); Feature f1 = new Feature("chr1", "a", "exon", Location.fromBio(100, 148, '+'), 0.0, 0, ""); Feature f2 = new Feature("chr1", "a", "exon", Location.fromBio(150, 250, '+'), 0.0, 0, ""); Feature f3 = new Feature("chr1", "a", "exon", Location.fromBio(260, 400, '+'), 0.0, 0, ""); Feature f4 = new Feature("chr1", "a", "exon", Location.fromBio(260, 300, '+'), 0.0, 0, ""); List<Feature> features = new LinkedList<Feature>(); features.add(f0); features.add(f1); features.add(f2); features.add(f3); features.add(f4); List<Feature> removed = FeatureMerger.removeOverlappingFeaturesIgnoreStrand(features); assertEquals(2,removed.size()); assertEquals(3,features.size()); assertEquals(260,removed.get(0).location().bioStart()); assertEquals(400,removed.get(0).location().bioEnd()); assertEquals(260,removed.get(1).location().bioStart()); assertEquals(300,removed.get(1).location().bioEnd()); assertEquals(1,features.get(0).location().bioStart()); assertEquals(50,features.get(0).location().bioEnd()); assertEquals(100,features.get(1).location().bioStart()); assertEquals(148,features.get(1).location().bioEnd()); assertEquals(150,features.get(2).location().bioStart()); assertEquals(250,features.get(2).location().bioEnd()); } @Test public void testRemoveOverlappingFeatures4() { Feature f0 = new Feature("chr1", "a", "exon", Location.fromBio(1, 261, '+'), 0.0, 0, ""); Feature f1 = new Feature("chr1", "a", "exon", Location.fromBio(100, 200, '+'), 0.0, 0, ""); Feature f2 = new Feature("chr1", "a", "exon", Location.fromBio(150, 250, '+'), 0.0, 0, ""); Feature f3 = new Feature("chr1", "a", "exon", Location.fromBio(260, 300, '+'), 0.0, 0, ""); Feature f4 = new Feature("chr1", "a", "exon", Location.fromBio(300, 400, '+'), 0.0, 0, ""); Feature f5 = new Feature("chr1", "a", "exon", Location.fromBio(500, 600, '+'), 0.0, 0, ""); List<Feature> features = new LinkedList<Feature>(); features.add(f0); features.add(f1); features.add(f2); features.add(f3); features.add(f4); features.add(f5); List<Feature> removed = FeatureMerger.removeOverlappingFeaturesIgnoreStrand(features); assertEquals(5,removed.size()); assertEquals(1,features.size()); assertEquals(100,removed.get(0).location().bioStart()); assertEquals(200,removed.get(0).location().bioEnd()); assertEquals(150,removed.get(1).location().bioStart()); assertEquals(250,removed.get(1).location().bioEnd()); assertEquals(1,removed.get(2).location().bioStart()); assertEquals(261,removed.get(2).location().bioEnd()); assertEquals(260,removed.get(3).location().bioStart()); assertEquals(300,removed.get(3).location().bioEnd()); assertEquals(300,removed.get(4).location().bioStart()); assertEquals(400,removed.get(4).location().bioEnd()); assertEquals(500,features.get(0).location().bioStart()); assertEquals(600,features.get(0).location().bioEnd()); } }
christopher-gillies/rna-seq-pipeline
src/test/java/org/kidneyomics/gtf/FeatureMergerTest.java
Java
gpl-2.0
9,180
function eliminarItem(id, url){ console.log("Eliminar Fase"); console.log(id); console.log(url); $("#nombre-item").text(id); $("#modal-eliminar").modal('show'); $("#btn-eliminar").attr('href', url); } function revivirItem(id, url){ console.log("Eliminar Fase"); console.log(id); console.log(url); $("#nombre-revivir-item").text(id); $("#modal-revivir").modal('show'); $("#btn-revivir").attr('href', url); } function revertirItem(version, id_version){ console.log("Revertir item"); console.log(id_version); $("#version-item").text(version); $("#id_version").val(id_version); $("#modal-revertir").modal('show'); } function modificarItem(id, codigo, nombre, descripcion){ console.log("MODIFICAR TIPO ITEM"); console.log(id) console.log(codigo); console.log(nombre); console.log(descripcion); console.log("------------------"); $("#m-id").val(id); $("#m-codigo").val(codigo) $("#m-nombre").val(nombre); $("#m-descripcion").val(descripcion); $("#modal-modificar").modal('show'); } function setUrlNewItem(id_fase){ var id_tipo = $("#id-tipo").val(); var url = "/item/" + id_fase + "/nuevo/" + id_tipo + "/"; console.log(url); $("#next-new-item").attr("href", url); } function setListaRelacion(){ var tipo = $("#tipo").val(); console.log(tipo) if(tipo == 'padre-hijo'){ console.log("tipo padre-hijo"); $("#s-hijo").removeClass('hide'); $("#s-sucesor").addClass('hide'); }else{ console.log("tipo antecesor-sucesor"); $("#s-sucesor").removeClass('hide'); $("#s-hijo").addClass('hide'); } } function eliminarRelacionItem(url){ console.log("Eliminar Relacion Item"); console.log(url); $("#modal-eliminar").modal('show'); $("#btn-eliminar").attr('href', url); } function adjuntarArchivo(nombre){ console.log("Adjuntar archivo a"); console.log(nombre); $("#modal-modificar").modal('show'); } function showImpacto(url){ $.get( url, function( data ) { console.log( "Load was performed." + data); var datos = JSON.parse(data); if( datos ){ var item = datos; console.log(item); $("#nombre-impacto-item").empty().append(""+item.nombre); $("#impacto-item").empty().append(""+item.impacto); $("#modal-impacto").modal('show'); } }); }
SantiagoValdez/hpm
src/hpm/static/js/item.js
JavaScript
gpl-2.0
2,276
<?php get_header(); ?> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <?php $attachment_link = get_the_attachment_link($post->ID, true, array(450, 800)); // This also populates the iconsize for the next line ?> <?php $_post = &get_post($post->ID); $classname = ($_post->iconsize[0] <= 128 ? 'small' : '') . 'attachment'; // This lets us style narrow icons specially ?> <div class="item_class" id="post-<?php the_ID(); ?>"> <div class="item_class_title"> <div class="item_class_title_text"> <div class="date"> <div class="date_month"><?php the_time('M') ?></div> <div class="date_day"><?php the_time('d') ?></div> </div> <div class="titles"> <div class="top_title"><h1><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php _e('Permanent Link to',TEMPLATE_DOMAIN);?> <?php the_title(); ?>"><?php the_title(); ?></a></h1></div> <div class="end_title"><?php _e("Filed Under",TEMPLATE_DOMAIN); ?> (<?php the_category(', ') ?>) <?php _e("by",TEMPLATE_DOMAIN); ?> <?php the_author() ?> <?php _e('on',TEMPLATE_DOMAIN);?> <?php the_time('d-m-Y') ?></div> </div> </div> </div> <div class="item_class_text"> <?php the_content(__('Read the rest of this entry &raquo;',TEMPLATE_DOMAIN)); ?> </div> <div class="item_class_panel"> <div> <div class="links_left"> <span class="panel_comm"><a href="<?php the_permalink() ?>#respond"><?php _e("Post a Comment",TEMPLATE_DOMAIN); ?></a></span>&nbsp;&nbsp;&nbsp; <?php edit_post_link(__('Edit',TEMPLATE_DOMAIN), '', ''); ?> </div> <div class="links_right"> <?php comments_popup_link(__('(0) Comments',TEMPLATE_DOMAIN), __('(1) Comment',TEMPLATE_DOMAIN), __('(%) Comments',TEMPLATE_DOMAIN)); ?>&nbsp;&nbsp; <a href="<?php the_permalink() ?>" class="panel_read"><?php _e("Read More",TEMPLATE_DOMAIN); ?></a> </div> </div> </div> </div> <?php if ( comments_open() ) { ?> <?php comments_template('',true); ?><?php } ?> <?php endwhile; else: ?> <div id="content" class="narrowcolumn"><p><?php _e('Sorry, no attachments matched your criteria.',TEMPLATE_DOMAIN);?></p> <?php _e('Both comments and pings are currently closed.',TEMPLATE_DOMAIN);?></div> <?php endif; ?> <?php get_footer(); ?>
rjbaniel/upoor
wp-content/themes/oceanwide/attachment.php
PHP
gpl-2.0
2,504
#include "yacss/CSSBaseValue.hh" namespace yacss { std::ostream& operator<< (std::ostream& o, const CSSBaseValue& val) { if (val.type == ValueType::Length) o << val.get<LengthValue>(); else if (val.type == ValueType::Keyword) o << val.get<KeywordValue>(); else if (val.type == ValueType::ColorRGBA) o << val.get<ColorRGBAValue>(); else throw std::runtime_error("CSSBaseValue << : Unknown Type."); return o; } }; // ! ns yacss
cirocosta/yacss-parser
src/CSSBaseValue.cc
C++
gpl-2.0
456
<?php /****************************************************** Open .node *** * Description: * Status: Stable. * Author: Alexandre Dath <alexandre@dotnode.com> * $Id$ * * Copyright (C) 2005 Alexandre Dath <alexandre@dotnode.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ******************** http://opensource.ikse.net/projects/dotnode ***/ define('INCLUDEPATH',BASEPATH.'/../inc'); define('ACTIONSPATH',BASEPATH.'/../actions'); define('RESPONSESPATH',BASEPATH.'/../responses'); define('CODEPIX_PATH',BASEPATH.'/../codepix'); ini_set('session.name','dotnodeSessID'); ini_set('session.save_path',BASEPATH.'/../sessions'); include(INCLUDESPATH.'/session_save_handler.inc.php'); session_set_save_handler ("_sess_open", "_sess_close", "_sess_read", "_sess_write", "_sess_destroy", "_sess_gc"); ?>
alex-ikse/dotnode
includes/config/global.inc.php
PHP
gpl-2.0
1,501
using System; using Server.Items; using Server.Targeting; namespace Server.Engines.Craft { public enum SmeltResult { Success, Invalid, NoSkill } public class Resmelt { public Resmelt() { } public static void Do(Mobile from, CraftSystem craftSystem, ITool tool) { int num = craftSystem.CanCraft(from, tool, null); if (num > 0 && num != 1044267) { from.SendGump(new CraftGump(from, craftSystem, tool, num)); } else { from.Target = new InternalTarget(craftSystem, tool); from.SendLocalizedMessage(1044273); // Target an item to recycle. } } private class InternalTarget : Target { private readonly CraftSystem m_CraftSystem; private readonly ITool m_Tool; public InternalTarget(CraftSystem craftSystem, ITool tool) : base(2, false, TargetFlags.None) { m_CraftSystem = craftSystem; m_Tool = tool; } protected override void OnTarget(Mobile from, object targeted) { int num = m_CraftSystem.CanCraft(from, m_Tool, null); if (num > 0) { if (num == 1044267) { bool anvil, forge; DefBlacksmithy.CheckAnvilAndForge(from, 2, out anvil, out forge); if (!anvil) num = 1044266; // You must be near an anvil else if (!forge) num = 1044265; // You must be near a forge. } from.SendGump(new CraftGump(from, m_CraftSystem, m_Tool, num)); } else { SmeltResult result = SmeltResult.Invalid; bool isStoreBought = false; int message; if (targeted is BaseArmor) { result = Resmelt(from, (BaseArmor)targeted, ((BaseArmor)targeted).Resource); isStoreBought = !((BaseArmor)targeted).PlayerConstructed; } else if (targeted is BaseWeapon) { result = Resmelt(from, (BaseWeapon)targeted, ((BaseWeapon)targeted).Resource); isStoreBought = !((BaseWeapon)targeted).PlayerConstructed; } else if (targeted is DragonBardingDeed) { result = Resmelt(from, (DragonBardingDeed)targeted, ((DragonBardingDeed)targeted).Resource); isStoreBought = false; } switch ( result ) { default: case SmeltResult.Invalid: message = 1044272; break; // You can't melt that down into ingots. case SmeltResult.NoSkill: message = 1044269; break; // You have no idea how to work this metal. case SmeltResult.Success: message = isStoreBought ? 500418 : 1044270; break; // You melt the item down into ingots. } from.SendGump(new CraftGump(from, m_CraftSystem, m_Tool, message)); } } private SmeltResult Resmelt(Mobile from, Item item, CraftResource resource) { try { if (CraftResources.GetType(resource) != CraftResourceType.Metal) return SmeltResult.Invalid; CraftResourceInfo info = CraftResources.GetInfo(resource); if (info == null || info.ResourceTypes.Length == 0) return SmeltResult.Invalid; CraftItem craftItem = m_CraftSystem.CraftItems.SearchFor(item.GetType()); if (craftItem == null || craftItem.Resources.Count == 0) return SmeltResult.Invalid; CraftRes craftResource = craftItem.Resources.GetAt(0); if (craftResource.Amount < 2) return SmeltResult.Invalid; // Not enough metal to resmelt double difficulty = 0.0; switch ( resource ) { case CraftResource.DullCopper: difficulty = 65.0; break; case CraftResource.ShadowIron: difficulty = 70.0; break; case CraftResource.Copper: difficulty = 75.0; break; case CraftResource.Bronze: difficulty = 80.0; break; case CraftResource.Gold: difficulty = 85.0; break; case CraftResource.Agapite: difficulty = 90.0; break; case CraftResource.Verite: difficulty = 95.0; break; case CraftResource.Valorite: difficulty = 99.0; break; } double skill = Math.Max(from.Skills[SkillName.Mining].Value, from.Skills[SkillName.Blacksmith].Value); if (difficulty > skill) return SmeltResult.NoSkill; Type resourceType = info.ResourceTypes[0]; Item ingot = (Item)Activator.CreateInstance(resourceType); if (item is DragonBardingDeed || (item is BaseArmor && ((BaseArmor)item).PlayerConstructed) || (item is BaseWeapon && ((BaseWeapon)item).PlayerConstructed) || (item is BaseClothing && ((BaseClothing)item).PlayerConstructed)) ingot.Amount = (int)((double)craftResource.Amount * .66); else ingot.Amount = 1; item.Delete(); from.AddToBackpack(ingot); from.PlaySound(0x2A); from.PlaySound(0x240); return SmeltResult.Success; } catch { } return SmeltResult.Invalid; } } } }
kevin-10/ServUO
Scripts/Services/Craft/Core/Resmelt.cs
C#
gpl-2.0
6,952
<?php /** * Plugin Update Checker Library 2.2.0 * http://w-shadow.com/ * * Copyright 2015 Janis Elsts * Released under the MIT license. See license.txt for details. */ if ( !class_exists('wcva_PluginUpdateChecker_2_2', false) ): /** * A custom plugin update checker. * * @author Janis Elsts * @copyright 2015 * @version 2.2 * @access public */ class wcva_PluginUpdateChecker_2_2 { public $metadataUrl = ''; //The URL of the plugin's metadata file. public $pluginAbsolutePath = ''; //Full path of the main plugin file. public $pluginFile = ''; //Plugin filename relative to the plugins directory. Many WP APIs use this to identify plugins. public $slug = ''; //Plugin slug. public $checkPeriod = 12; //How often to check for updates (in hours). public $optionName = ''; //Where to store the update info. public $muPluginFile = ''; //For MU plugins, the plugin filename relative to the mu-plugins directory. public $debugMode = false; //Set to TRUE to enable error reporting. Errors are raised using trigger_error() //and should be logged to the standard PHP error log. public $throttleRedundantChecks = false; //Check less often if we already know that an update is available. public $throttledCheckPeriod = 72; private $cronHook = null; private $debugBarPlugin = null; private $cachedInstalledVersion = null; private $upgradedPluginFile = null; //The plugin that is currently being upgraded by WordPress. /** * Class constructor. * * @param string $metadataUrl The URL of the plugin's metadata file. * @param string $pluginFile Fully qualified path to the main plugin file. * @param string $slug The plugin's 'slug'. If not specified, the filename part of $pluginFile sans '.php' will be used as the slug. * @param integer $checkPeriod How often to check for updates (in hours). Defaults to checking every 12 hours. Set to 0 to disable automatic update checks. * @param string $optionName Where to store book-keeping info about update checks. Defaults to 'external_updates-$slug'. * @param string $muPluginFile Optional. The plugin filename relative to the mu-plugins directory. */ public function __construct($metadataUrl, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = ''){ $this->purchase_url = ''.site_url().'/wp-admin/admin.php?page=wc-settings&tab=products&section=display#woocommerce_wcva_purchase_code'; $this->is_code_valid = get_option('wcva_activation_status'); $this->metadataUrl = $metadataUrl; $this->pluginAbsolutePath = $pluginFile; $this->pluginFile = plugin_basename($this->pluginAbsolutePath); $this->muPluginFile = $muPluginFile; $this->checkPeriod = $checkPeriod; $this->slug = $slug; $this->optionName = $optionName; $this->debugMode = defined('WP_DEBUG') && WP_DEBUG; //If no slug is specified, use the name of the main plugin file as the slug. //For example, 'my-cool-plugin/cool-plugin.php' becomes 'cool-plugin'. if ( empty($this->slug) ){ $this->slug = basename($this->pluginFile, '.php'); } if ( empty($this->optionName) ){ $this->optionName = 'external_updates-' . $this->slug; } //Backwards compatibility: If the plugin is a mu-plugin but no $muPluginFile is specified, assume //it's the same as $pluginFile given that it's not in a subdirectory (WP only looks in the base dir). if ( empty($this->muPluginFile) && (strpbrk($this->pluginFile, '/\\') === false) && $this->isMuPlugin() ) { $this->muPluginFile = $this->pluginFile; } $this->installHooks(); } /** * Install the hooks required to run periodic update checks and inject update info * into WP data structures. * * @return void */ protected function installHooks(){ //Override requests for plugin information add_filter('plugins_api', array($this, 'injectInfo'), 20, 3); //Insert our update info into the update array maintained by WP add_filter('site_transient_update_plugins', array($this,'injectUpdate')); //WP 3.0+ add_filter('transient_update_plugins', array($this,'injectUpdate')); //WP 2.8+ add_filter('plugin_row_meta', array($this, 'addCheckForUpdatesLink'), 10, 2); add_action('admin_init', array($this, 'handleManualCheck')); add_action('all_admin_notices', array($this, 'displayManualCheckResult')); //Clear the version number cache when something - anything - is upgraded or WP clears the update cache. add_filter('upgrader_post_install', array($this, 'clearCachedVersion')); add_action('delete_site_transient_update_plugins', array($this, 'clearCachedVersion')); //Set up the periodic update checks $this->cronHook = 'check_plugin_updates-' . $this->slug; if ( $this->checkPeriod > 0 ){ //Trigger the check via Cron. //Try to use one of the default schedules if possible as it's less likely to conflict //with other plugins and their custom schedules. $defaultSchedules = array( 1 => 'hourly', 12 => 'twicedaily', 24 => 'daily', ); if ( array_key_exists($this->checkPeriod, $defaultSchedules) ) { $scheduleName = $defaultSchedules[$this->checkPeriod]; } else { //Use a custom cron schedule. $scheduleName = 'every' . $this->checkPeriod . 'hours'; add_filter('cron_schedules', array($this, '_addCustomSchedule')); } if ( !wp_next_scheduled($this->cronHook) && !defined('WP_INSTALLING') ) { wp_schedule_event(time(), $scheduleName, $this->cronHook); } add_action($this->cronHook, array($this, 'maybeCheckForUpdates')); register_deactivation_hook($this->pluginFile, array($this, '_removeUpdaterCron')); //In case Cron is disabled or unreliable, we also manually trigger //the periodic checks while the user is browsing the Dashboard. add_action( 'admin_init', array($this, 'maybeCheckForUpdates') ); //Like WordPress itself, we check more often on certain pages. /** @see wp_update_plugins */ add_action('load-update-core.php', array($this, 'maybeCheckForUpdates')); add_action('load-plugins.php', array($this, 'maybeCheckForUpdates')); add_action('load-update.php', array($this, 'maybeCheckForUpdates')); //This hook fires after a bulk update is complete. add_action('upgrader_process_complete', array($this, 'maybeCheckForUpdates'), 11, 0); } else { //Periodic checks are disabled. wp_clear_scheduled_hook($this->cronHook); } if ( did_action('plugins_loaded') ) { $this->initDebugBarPanel(); } else { add_action('plugins_loaded', array($this, 'initDebugBarPanel')); } //Rename the update directory to be the same as the existing directory. add_filter('upgrader_source_selection', array($this, 'fixDirectoryName'), 10, 3); //Keep track of which plugin WordPress is currently upgrading. add_filter('upgrader_pre_install', array($this, 'setUpgradedPlugin'), 10, 2); add_filter('upgrader_post_install', array($this, 'clearUpgradedPlugin'), 10, 1); add_action('upgrader_process_complete', array($this, 'clearUpgradedPlugin'), 10, 1); } /** * Add our custom schedule to the array of Cron schedules used by WP. * * @param array $schedules * @return array */ public function _addCustomSchedule($schedules){ if ( $this->checkPeriod && ($this->checkPeriod > 0) ){ $scheduleName = 'every' . $this->checkPeriod . 'hours'; $schedules[$scheduleName] = array( 'interval' => $this->checkPeriod * 3600, 'display' => sprintf('Every %d hours', $this->checkPeriod), ); } return $schedules; } /** * Remove the scheduled cron event that the library uses to check for updates. * * @return void */ public function _removeUpdaterCron(){ wp_clear_scheduled_hook($this->cronHook); } /** * Get the name of the update checker's WP-cron hook. Mostly useful for debugging. * * @return string */ public function getCronHookName() { return $this->cronHook; } /** * Retrieve plugin info from the configured API endpoint. * * @uses wp_remote_get() * * @param array $queryArgs Additional query arguments to append to the request. Optional. * @return PluginInfo */ public function requestInfo($queryArgs = array()){ //Query args to append to the URL. Plugins can add their own by using a filter callback (see addQueryArgFilter()). $installedVersion = $this->getInstalledVersion(); $queryArgs['installed_version'] = ($installedVersion !== null) ? $installedVersion : ''; $queryArgs = apply_filters('puc_request_info_query_args-'.$this->slug, $queryArgs); //Various options for the wp_remote_get() call. Plugins can filter these, too. $options = array( 'timeout' => 10, //seconds 'headers' => array( 'Accept' => 'application/json' ), ); $options = apply_filters('puc_request_info_options-'.$this->slug, $options); //The plugin info should be at 'http://your-api.com/url/here/$slug/info.json' $url = $this->metadataUrl; if ( !empty($queryArgs) ){ $url = add_query_arg($queryArgs, $url); } $result = wp_remote_get( $url, $options ); //Try to parse the response $pluginInfo = null; if ( !is_wp_error($result) && isset($result['response']['code']) && ($result['response']['code'] == 200) && !empty($result['body']) ){ $pluginInfo = wcva_PluginInfo_2_2::fromJson($result['body'], $this->debugMode); $pluginInfo->filename = $this->pluginFile; $pluginInfo->slug = $this->slug; } else if ( $this->debugMode ) { $message = sprintf("The URL %s does not point to a valid plugin metadata file. ", $url); if ( is_wp_error($result) ) { $message .= "WP HTTP error: " . $result->get_error_message(); } else if ( isset($result['response']['code']) ) { $message .= "HTTP response code is " . $result['response']['code'] . " (expected: 200)"; } else { $message .= "wp_remote_get() returned an unexpected result."; } trigger_error($message, E_USER_WARNING); } $pluginInfo = apply_filters('puc_request_info_result-'.$this->slug, $pluginInfo, $result); return $pluginInfo; } /** * Retrieve the latest update (if any) from the configured API endpoint. * * @uses PluginUpdateChecker::requestInfo() * * @return PluginUpdate An instance of PluginUpdate, or NULL when no updates are available. */ public function requestUpdate(){ //For the sake of simplicity, this function just calls requestInfo() //and transforms the result accordingly. $pluginInfo = $this->requestInfo(array('checking_for_updates' => '1')); if ( $pluginInfo == null ){ return null; } return wcva_PluginUpdate_2_2::fromPluginInfo($pluginInfo); } /** * Get the currently installed version of the plugin. * * @return string Version number. */ public function getInstalledVersion(){ if ( isset($this->cachedInstalledVersion) ) { return $this->cachedInstalledVersion; } $pluginHeader = $this->getPluginHeader(); if ( isset($pluginHeader['Version']) ) { $this->cachedInstalledVersion = $pluginHeader['Version']; return $pluginHeader['Version']; } else { //This can happen if the filename points to something that is not a plugin. if ( $this->debugMode ) { trigger_error( sprintf( "Can't to read the Version header for '%s'. The filename is incorrect or is not a plugin.", $this->pluginFile ), E_USER_WARNING ); } return null; } } /** * Get plugin's metadata from its file header. * * @return array */ protected function getPluginHeader() { if ( !is_file($this->pluginAbsolutePath) ) { //This can happen if the plugin filename is wrong. if ( $this->debugMode ) { trigger_error( sprintf( "Can't to read the plugin header for '%s'. The file does not exist.", $this->pluginFile ), E_USER_WARNING ); } return array(); } if ( !function_exists('get_plugin_data') ){ require_once( ABSPATH . '/wp-admin/includes/plugin.php' ); } return get_plugin_data($this->pluginAbsolutePath, false, false); } /** * Check for plugin updates. * The results are stored in the DB option specified in $optionName. * * @return PluginUpdate|null */ public function checkForUpdates(){ wcva_verify_envato_purchase_code(); $installedVersion = $this->getInstalledVersion(); //Fail silently if we can't find the plugin or read its header. if ( $installedVersion === null ) { if ( $this->debugMode ) { trigger_error( sprintf('Skipping update check for %s - installed version unknown.', $this->pluginFile), E_USER_WARNING ); } return null; } $state = $this->getUpdateState(); if ( empty($state) ){ $state = new StdClass; $state->lastCheck = 0; $state->checkedVersion = ''; $state->update = null; } $state->lastCheck = time(); $state->checkedVersion = $installedVersion; $this->setUpdateState($state); //Save before checking in case something goes wrong $state->update = $this->requestUpdate(); $this->setUpdateState($state); return $this->getUpdate(); } /** * Check for updates if the configured check interval has already elapsed. * Will use a shorter check interval on certain admin pages like "Dashboard -> Updates" or when doing cron. * * You can override the default behaviour by using the "puc_check_now-$slug" filter. * The filter callback will be passed three parameters: * - Current decision. TRUE = check updates now, FALSE = don't check now. * - Last check time as a Unix timestamp. * - Configured check period in hours. * Return TRUE to check for updates immediately, or FALSE to cancel. * * This method is declared public because it's a hook callback. Calling it directly is not recommended. */ public function maybeCheckForUpdates(){ if ( empty($this->checkPeriod) ){ return; } $currentFilter = current_filter(); if ( in_array($currentFilter, array('load-update-core.php', 'upgrader_process_complete')) ) { //Check more often when the user visits "Dashboard -> Updates" or does a bulk update. $timeout = 60; } else if ( in_array($currentFilter, array('load-plugins.php', 'load-update.php')) ) { //Also check more often on the "Plugins" page and /wp-admin/update.php. $timeout = 3600; } else if ( $this->throttleRedundantChecks && ($this->getUpdate() !== null) ) { //Check less frequently if it's already known that an update is available. $timeout = $this->throttledCheckPeriod * 3600; } else if ( defined('DOING_CRON') && constant('DOING_CRON') ) { //WordPress cron schedules are not exact, so lets do an update check even //if slightly less than $checkPeriod hours have elapsed since the last check. $cronFuzziness = 20 * 60; $timeout = $this->checkPeriod * 3600 - $cronFuzziness; } else { $timeout = $this->checkPeriod * 3600; } $state = $this->getUpdateState(); $shouldCheck = empty($state) || !isset($state->lastCheck) || ( (time() - $state->lastCheck) >= $timeout ); //Let plugin authors substitute their own algorithm. $shouldCheck = apply_filters( 'puc_check_now-' . $this->slug, $shouldCheck, (!empty($state) && isset($state->lastCheck)) ? $state->lastCheck : 0, $this->checkPeriod ); if ( $shouldCheck ){ $this->checkForUpdates(); } } /** * Load the update checker state from the DB. * * @return StdClass|null */ public function getUpdateState() { $state = get_site_option($this->optionName, null); if ( empty($state) || !is_object($state)) { $state = null; } if ( !empty($state) && isset($state->update) && is_object($state->update) ){ $state->update = wcva_PluginUpdate_2_2::fromObject($state->update); } return $state; } /** * Persist the update checker state to the DB. * * @param StdClass $state * @return void */ private function setUpdateState($state) { if ( isset($state->update) && is_object($state->update) && method_exists($state->update, 'toStdClass') ) { $update = $state->update; /** @var PluginUpdate $update */ $state->update = $update->toStdClass(); } update_site_option($this->optionName, $state); } /** * Reset update checker state - i.e. last check time, cached update data and so on. * * Call this when your plugin is being uninstalled, or if you want to * clear the update cache. */ public function resetUpdateState() { delete_site_option($this->optionName); } /** * Intercept plugins_api() calls that request information about our plugin and * use the configured API endpoint to satisfy them. * * @see plugins_api() * * @param mixed $result * @param string $action * @param array|object $args * @return mixed */ public function injectInfo($result, $action = null, $args = null){ $relevant = ($action == 'plugin_information') && isset($args->slug) && ( ($args->slug == $this->slug) || ($args->slug == dirname($this->pluginFile)) ); if ( !$relevant ){ return $result; } $pluginInfo = $this->requestInfo(); $pluginInfo = apply_filters('puc_pre_inject_info-' . $this->slug, $pluginInfo); if ($pluginInfo){ return $pluginInfo->toWpFormat(); } return $result; } /** * Insert the latest update (if any) into the update list maintained by WP. * * @param StdClass $updates Update list. * @return StdClass Modified update list. */ public function injectUpdate($updates){ //Is there an update to insert? $update = $this->getUpdate(); //No update notifications for mu-plugins unless explicitly enabled. The MU plugin file //is usually different from the main plugin file so the update wouldn't show up properly anyway. if ( !empty($update) && empty($this->muPluginFile) && $this->isMuPlugin() ) { $update = null; } if ( !empty($update) ) { //Let plugins filter the update info before it's passed on to WordPress. $update = apply_filters('puc_pre_inject_update-' . $this->slug, $update); if ( !is_object($updates) ) { $updates = new StdClass(); $updates->response = array(); } $wpUpdate = $update->toWpFormat(); $pluginFile = $this->pluginFile; if ( $this->isMuPlugin() ) { //WP does not support automatic update installation for mu-plugins, but we can still display a notice. $wpUpdate->package = null; $pluginFile = $this->muPluginFile; } $updates->response[$pluginFile] = $wpUpdate; } else if ( isset($updates, $updates->response) ) { unset($updates->response[$this->pluginFile]); if ( !empty($this->muPluginFile) ) { unset($updates->response[$this->muPluginFile]); } } return $updates; } /** * Rename the update directory to match the existing plugin directory. * * When WordPress installs a plugin or theme update, it assumes that the ZIP file will contain * exactly one directory, and that the directory name will be the same as the directory where * the plugin/theme is currently installed. * * GitHub and other repositories provide ZIP downloads, but they often use directory names like * "project-branch" or "project-tag-hash". We need to change the name to the actual plugin folder. * * @param string $source The directory to copy to /wp-content/plugins. Usually a subdirectory of $remoteSource. * @param string $remoteSource WordPress has extracted the update to this directory. * @param WP_Upgrader $upgrader * @return string|WP_Error */ function fixDirectoryName($source, $remoteSource, $upgrader) { global $wp_filesystem; /** @var WP_Filesystem_Base $wp_filesystem */ //Basic sanity checks. if ( !isset($source, $remoteSource, $upgrader, $upgrader->skin, $wp_filesystem) ) { return $source; } //Figure out which plugin is being upgraded. $pluginFile = null; $skin = $upgrader->skin; if ( $skin instanceof Plugin_Upgrader_Skin ) { if ( isset($skin->plugin) && is_string($skin->plugin) && ($skin->plugin !== '') ) { $pluginFile = $skin->plugin; } } elseif ( isset($skin->plugin_info) && is_array($skin->plugin_info) ) { //This case is tricky because Bulk_Plugin_Upgrader_Skin (etc) doesn't actually store the plugin //filename anywhere. Instead, it has the plugin headers in $plugin_info. So the best we can //do is compare those headers to the headers of installed plugins. if ( !function_exists('get_plugins') ){ require_once( ABSPATH . '/wp-admin/includes/plugin.php' ); } $installedPlugins = get_plugins(); $matches = array(); foreach($installedPlugins as $pluginBasename => $headers) { $diff1 = array_diff_assoc($headers, $skin->plugin_info); $diff2 = array_diff_assoc($skin->plugin_info, $headers); if ( empty($diff1) && empty($diff2) ) { $matches[] = $pluginBasename; } } //It's possible (though very unlikely) that there could be two plugins with identical //headers. In that case, we can't unambiguously identify the plugin that's being upgraded. if ( count($matches) !== 1 ) { return $source; } $pluginFile = reset($matches); } elseif ( !empty($this->upgradedPluginFile) ) { $pluginFile = $this->upgradedPluginFile; } //If WordPress is upgrading anything other than our plugin, leave the directory name unchanged. if ( empty($pluginFile) || ($pluginFile !== $this->pluginFile) ) { return $source; } //Rename the source to match the existing plugin directory. $pluginDirectoryName = dirname($this->pluginFile); if ( ($pluginDirectoryName === '.') || ($pluginDirectoryName === '/') ) { return $source; } $correctedSource = trailingslashit($remoteSource) . $pluginDirectoryName . '/'; if ( $source !== $correctedSource ) { //The update archive should contain a single directory that contains the rest of plugin files. Otherwise, //WordPress will try to copy the entire working directory ($source == $remoteSource). We can't rename //$remoteSource because that would break WordPress code that cleans up temporary files after update. $sourceFiles = $wp_filesystem->dirlist($remoteSource); if ( is_array($sourceFiles) ) { $sourceFiles = array_keys($sourceFiles); $firstFilePath = trailingslashit($remoteSource) . $sourceFiles[0]; if ( (count($sourceFiles) > 1) || (!$wp_filesystem->is_dir($firstFilePath)) ) { return new WP_Error( 'puc-incorrect-directory-structure', sprintf( 'The directory structure of the update is incorrect. All plugin files should be inside ' . 'a directory named <span class="code">%s</span>, not at the root of the ZIP file.', htmlentities($this->slug) ) ); } } $upgrader->skin->feedback(sprintf( 'Renaming %s to %s&#8230;', '<span class="code">' . basename($source) . '</span>', '<span class="code">' . $pluginDirectoryName . '</span>' )); if ( $wp_filesystem->move($source, $correctedSource, true) ) { $upgrader->skin->feedback('Plugin directory successfully renamed.'); return $correctedSource; } else { return new WP_Error( 'puc-rename-failed', 'Unable to rename the update to match the existing plugin directory.' ); } } return $source; } /** * @access private * * @param mixed $input * @param array $hookExtra * @return mixed Returns $input unaltered. */ public function setUpgradedPlugin($input, $hookExtra) { if (!empty($hookExtra['plugin']) && is_string($hookExtra['plugin'])) { $this->upgradedPluginFile = $hookExtra['plugin']; } else { $this->upgradedPluginFile = null; } return $input; } /** * @access private * * @param mixed $input * @return mixed Returns $input unaltered. */ public function clearUpgradedPlugin($input = null) { $this->upgradedPluginFile = null; return $input; } /** * Get the details of the currently available update, if any. * * If no updates are available, or if the last known update version is below or equal * to the currently installed version, this method will return NULL. * * Uses cached update data. To retrieve update information straight from * the metadata URL, call requestUpdate() instead. * * @return PluginUpdate|null */ public function getUpdate() { $state = $this->getUpdateState(); /** @var StdClass $state */ //Is there an update available insert? if ( !empty($state) && isset($state->update) && !empty($state->update) ){ $update = $state->update; //Check if the update is actually newer than the currently installed version. $installedVersion = $this->getInstalledVersion(); if ( ($installedVersion !== null) && version_compare($update->version, $installedVersion, '>') ){ $update->filename = $this->pluginFile; return $update; } } return null; } /** * Add a "Check for updates" link to the plugin row in the "Plugins" page. By default, * the new link will appear after the "Visit plugin site" link. * * You can change the link text by using the "puc_manual_check_link-$slug" filter. * Returning an empty string from the filter will disable the link. * * @param array $pluginMeta Array of meta links. * @param string $pluginFile * @return array */ public function addCheckForUpdatesLink($pluginMeta, $pluginFile) { $isRelevant = ($pluginFile == $this->pluginFile) || (!empty($this->muPluginFile) && $pluginFile == $this->muPluginFile); if ( $isRelevant && current_user_can('update_plugins') ) { $linkUrl = wp_nonce_url( add_query_arg( array( 'puc_check_for_updates' => 1, 'puc_slug' => $this->slug, ), is_network_admin() ? network_admin_url('plugins.php') : admin_url('plugins.php') ), 'puc_check_for_updates' ); $linkText = apply_filters('puc_manual_check_link-' . $this->slug, 'Check for updates'); if ( !empty($linkText) ) { $pluginMeta[] = sprintf('<a href="%s">%s</a>', esc_attr($linkUrl), $linkText); } } return $pluginMeta; } /** * Check for updates when the user clicks the "Check for updates" link. * @see self::addCheckForUpdatesLink() * * @return void */ public function handleManualCheck() { $shouldCheck = isset($_GET['puc_check_for_updates'], $_GET['puc_slug']) && $_GET['puc_slug'] == $this->slug && current_user_can('update_plugins') && check_admin_referer('puc_check_for_updates'); if ( $shouldCheck ) { $update = $this->checkForUpdates(); $status = ($update === null) ? 'no_update' : 'update_available'; wp_redirect(add_query_arg( array( 'puc_update_check_result' => $status, 'puc_slug' => $this->slug, ), is_network_admin() ? network_admin_url('plugins.php') : admin_url('plugins.php') )); } } /** * Display the results of a manual update check. * @see self::handleManualCheck() * * You can change the result message by using the "puc_manual_check_message-$slug" filter. */ public function displayManualCheckResult() { if ( isset($_GET['puc_update_check_result'], $_GET['puc_slug']) && ($_GET['puc_slug'] == $this->slug) ) { $status = strval($_GET['puc_update_check_result']); if ( $status == 'no_update' ) { $message = 'This plugin is up to date.'; } else if ( $status == 'update_available' ) { if (($this->is_code_valid) == "active") { $message = 'A new version of this plugin is available'; } else { $message= sprintf( 'A new version of woocommerce color or image variation swatches plugin is available. Please enter valid <a href="%s"><span> purchase code</span></a> to get the update.', $this->purchase_url ); } } else { $message = sprintf('Unknown update checker status "%s"', htmlentities($status)); } printf( '<div class="updated"><p>%s</p></div>', apply_filters('puc_manual_check_message-' . $this->slug, $message, $status) ); } } /** * Check if the plugin file is inside the mu-plugins directory. * * @return bool */ protected function isMuPlugin() { static $cachedResult = null; if ( $cachedResult === null ) { //Convert both paths to the canonical form before comparison. $muPluginDir = realpath(WPMU_PLUGIN_DIR); $pluginPath = realpath($this->pluginAbsolutePath); $cachedResult = (strpos($pluginPath, $muPluginDir) === 0); } return $cachedResult; } /** * Clear the cached plugin version. This method can be set up as a filter (hook) and will * return the filter argument unmodified. * * @param mixed $filterArgument * @return mixed */ public function clearCachedVersion($filterArgument = null) { $this->cachedInstalledVersion = null; return $filterArgument; } /** * Register a callback for filtering query arguments. * * The callback function should take one argument - an associative array of query arguments. * It should return a modified array of query arguments. * * @uses add_filter() This method is a convenience wrapper for add_filter(). * * @param callable $callback * @return void */ public function addQueryArgFilter($callback){ add_filter('puc_request_info_query_args-'.$this->slug, $callback); } /** * Register a callback for filtering arguments passed to wp_remote_get(). * * The callback function should take one argument - an associative array of arguments - * and return a modified array or arguments. See the WP documentation on wp_remote_get() * for details on what arguments are available and how they work. * * @uses add_filter() This method is a convenience wrapper for add_filter(). * * @param callable $callback * @return void */ public function addHttpRequestArgFilter($callback){ add_filter('puc_request_info_options-'.$this->slug, $callback); } /** * Register a callback for filtering the plugin info retrieved from the external API. * * The callback function should take two arguments. If the plugin info was retrieved * successfully, the first argument passed will be an instance of PluginInfo. Otherwise, * it will be NULL. The second argument will be the corresponding return value of * wp_remote_get (see WP docs for details). * * The callback function should return a new or modified instance of PluginInfo or NULL. * * @uses add_filter() This method is a convenience wrapper for add_filter(). * * @param callable $callback * @return void */ public function addResultFilter($callback){ add_filter('puc_request_info_result-'.$this->slug, $callback, 10, 2); } /** * Register a callback for one of the update checker filters. * * Identical to add_filter(), except it automatically adds the "puc_" prefix * and the "-$plugin_slug" suffix to the filter name. For example, "request_info_result" * becomes "puc_request_info_result-your_plugin_slug". * * @param string $tag * @param callable $callback * @param int $priority * @param int $acceptedArgs */ public function addFilter($tag, $callback, $priority = 10, $acceptedArgs = 1) { add_filter('puc_' . $tag . '-' . $this->slug, $callback, $priority, $acceptedArgs); } /** * Initialize the update checker Debug Bar plugin/add-on thingy. */ public function initDebugBarPanel() { $debugBarPlugin = dirname(__FILE__) . '/debug-bar-plugin.php'; if ( class_exists('Debug_Bar', false) && file_exists($debugBarPlugin) ) { require_once $debugBarPlugin; $this->debugBarPlugin = new PucDebugBarPlugin($this); } } } endif; if ( !class_exists('wcva_PluginInfo_2_2', false) ): /** * A container class for holding and transforming various plugin metadata. * * @author Janis Elsts * @copyright 2015 * @version 2.2 * @access public */ class wcva_PluginInfo_2_2 { //Most fields map directly to the contents of the plugin's info.json file. //See the relevant docs for a description of their meaning. public $name; public $slug; public $version; public $homepage; public $sections; public $banners; public $download_url; public $author; public $author_homepage; public $requires; public $tested; public $upgrade_notice; public $rating; public $num_ratings; public $downloaded; public $active_installs; public $last_updated; public $id = 0; //The native WP.org API returns numeric plugin IDs, but they're not used for anything. public $filename; //Plugin filename relative to the plugins directory. /** * Create a new instance of PluginInfo from JSON-encoded plugin info * returned by an external update API. * * @param string $json Valid JSON string representing plugin info. * @param bool $triggerErrors * @return PluginInfo|null New instance of PluginInfo, or NULL on error. */ public static function fromJson($json, $triggerErrors = false){ /** @var StdClass $apiResponse */ $apiResponse = json_decode($json); if ( empty($apiResponse) || !is_object($apiResponse) ){ if ( $triggerErrors ) { trigger_error( "Failed to parse plugin metadata. Try validating your .json file with http://jsonlint.com/", E_USER_NOTICE ); } return null; } //Very, very basic validation. $valid = isset($apiResponse->name) && !empty($apiResponse->name) && isset($apiResponse->version) && !empty($apiResponse->version); if ( !$valid ){ if ( $triggerErrors ) { trigger_error( "The plugin metadata file does not contain the required 'name' and/or 'version' keys.", E_USER_NOTICE ); } return null; } $info = new self(); foreach(get_object_vars($apiResponse) as $key => $value){ $info->$key = $value; } return $info; } /** * Transform plugin info into the format used by the native WordPress.org API * * @return object */ public function toWpFormat(){ $info = new StdClass; //The custom update API is built so that many fields have the same name and format //as those returned by the native WordPress.org API. These can be assigned directly. $sameFormat = array( 'name', 'slug', 'version', 'requires', 'tested', 'rating', 'upgrade_notice', 'num_ratings', 'downloaded', 'active_installs', 'homepage', 'last_updated', ); foreach($sameFormat as $field){ if ( isset($this->$field) ) { $info->$field = $this->$field; } else { $info->$field = null; } } //Other fields need to be renamed and/or transformed. $info->download_link = $this->download_url; if ( !empty($this->author_homepage) ){ $info->author = sprintf('<a href="%s">%s</a>', $this->author_homepage, $this->author); } else { $info->author = $this->author; } if ( is_object($this->sections) ){ $info->sections = get_object_vars($this->sections); } elseif ( is_array($this->sections) ) { $info->sections = $this->sections; } else { $info->sections = array('description' => ''); } if ( !empty($this->banners) ) { //WP expects an array with two keys: "high" and "low". Both are optional. //Docs: https://wordpress.org/plugins/about/faq/#banners $info->banners = is_object($this->banners) ? get_object_vars($this->banners) : $this->banners; $info->banners = array_intersect_key($info->banners, array('high' => true, 'low' => true)); } return $info; } } endif; if ( !class_exists('wcva_PluginUpdate_2_2', false) ): /** * A simple container class for holding information about an available update. * * @author Janis Elsts * @copyright 2015 * @version 2.2 * @access public */ class wcva_PluginUpdate_2_2 { public $id = 0; public $slug; public $version; public $homepage; public $download_url; public $upgrade_notice; public $filename; //Plugin filename relative to the plugins directory. private static $fields = array('id', 'slug', 'version', 'homepage', 'download_url', 'upgrade_notice', 'filename'); /** * Create a new instance of PluginUpdate from its JSON-encoded representation. * * @param string $json * @param bool $triggerErrors * @return PluginUpdate|null */ public static function fromJson($json, $triggerErrors = false){ //Since update-related information is simply a subset of the full plugin info, //we can parse the update JSON as if it was a plugin info string, then copy over //the parts that we care about. $pluginInfo = wcva_PluginInfo_2_2::fromJson($json, $triggerErrors); if ( $pluginInfo != null ) { return self::fromPluginInfo($pluginInfo); } else { return null; } } /** * Create a new instance of PluginUpdate based on an instance of PluginInfo. * Basically, this just copies a subset of fields from one object to another. * * @param PluginInfo $info * @return PluginUpdate */ public static function fromPluginInfo($info){ return self::fromObject($info); } /** * Create a new instance of PluginUpdate by copying the necessary fields from * another object. * * @param StdClass|PluginInfo|PluginUpdate $object The source object. * @return PluginUpdate The new copy. */ public static function fromObject($object) { $update = new self(); $fields = self::$fields; if (!empty($object->slug)) $fields = apply_filters('puc_retain_fields-'.$object->slug, $fields); foreach($fields as $field){ if (property_exists($object, $field)) { $update->$field = $object->$field; } } return $update; } /** * Create an instance of StdClass that can later be converted back to * a PluginUpdate. Useful for serialization and caching, as it avoids * the "incomplete object" problem if the cached value is loaded before * this class. * * @return StdClass */ public function toStdClass() { $object = new StdClass(); $fields = self::$fields; if (!empty($this->slug)) $fields = apply_filters('puc_retain_fields-'.$this->slug, $fields); foreach($fields as $field){ if (property_exists($this, $field)) { $object->$field = $this->$field; } } return $object; } /** * Transform the update into the format used by WordPress native plugin API. * * @return object */ public function toWpFormat(){ $update = new StdClass; $update->id = $this->id; $update->slug = $this->slug; $update->new_version = $this->version; $update->url = $this->homepage; $update->package = $this->download_url; $update->plugin = $this->filename; if ( !empty($this->upgrade_notice) ){ $update->upgrade_notice = $this->upgrade_notice; } $is_code_valid = get_option("wcva_activation_status"); if ( $is_code_valid == "active" ) { return $update; } } } endif; if ( !class_exists('PucFactory', false) ): /** * A factory that builds instances of other classes from this library. * * When multiple versions of the same class have been loaded (e.g. PluginUpdateChecker 1.2 * and 1.3), this factory will always use the latest available version. Register class * versions by calling {@link PucFactory::addVersion()}. * * At the moment it can only build instances of the PluginUpdateChecker class. Other classes * are intended mainly for internal use and refer directly to specific implementations. If you * want to instantiate one of them anyway, you can use {@link PucFactory::getLatestClassVersion()} * to get the class name and then create it with <code>new $class(...)</code>. */ class PucFactory { protected static $classVersions = array(); protected static $sorted = false; /** * Create a new instance of PluginUpdateChecker. * * @see PluginUpdateChecker::__construct() * * @param $metadataUrl * @param $pluginFile * @param string $slug * @param int $checkPeriod * @param string $optionName * @param string $muPluginFile * @return PluginUpdateChecker */ public static function buildUpdateChecker($metadataUrl, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = '') { $class = self::getLatestClassVersion('PluginUpdateChecker'); return new $class($metadataUrl, $pluginFile, $slug, $checkPeriod, $optionName, $muPluginFile); } /** * Get the specific class name for the latest available version of a class. * * @param string $class * @return string|null */ public static function getLatestClassVersion($class) { if ( !self::$sorted ) { self::sortVersions(); } if ( isset(self::$classVersions[$class]) ) { return reset(self::$classVersions[$class]); } else { return null; } } /** * Sort available class versions in descending order (i.e. newest first). */ protected static function sortVersions() { foreach ( self::$classVersions as $class => $versions ) { uksort($versions, array(__CLASS__, 'compareVersions')); self::$classVersions[$class] = $versions; } self::$sorted = true; } protected static function compareVersions($a, $b) { return -version_compare($a, $b); } /** * Register a version of a class. * * @access private This method is only for internal use by the library. * * @param string $generalClass Class name without version numbers, e.g. 'PluginUpdateChecker'. * @param string $versionedClass Actual class name, e.g. 'PluginUpdateChecker_1_2'. * @param string $version Version number, e.g. '1.2'. */ public static function addVersion($generalClass, $versionedClass, $version) { if ( !isset(self::$classVersions[$generalClass]) ) { self::$classVersions[$generalClass] = array(); } self::$classVersions[$generalClass][$version] = $versionedClass; self::$sorted = false; } } endif; require_once(dirname(__FILE__) . '/github-checker.php'); //Register classes defined in this file with the factory. PucFactory::addVersion('PluginUpdateChecker', 'wcva_PluginUpdateChecker_2_2', '2.2'); PucFactory::addVersion('PluginUpdate', 'wcva_PluginUpdate_2_2', '2.2'); PucFactory::addVersion('PluginInfo', 'wcva_PluginInfo_2_2', '2.2'); PucFactory::addVersion('PucGitHubChecker', 'PucGitHubChecker_2_2', '2.2'); /** * Create non-versioned variants of the update checker classes. This allows for backwards * compatibility with versions that did not use a factory, and it simplifies doc-comments. */ if ( !class_exists('PluginUpdateChecker', false) ) { class PluginUpdateChecker extends wcva_PluginUpdateChecker_2_2 { } } if ( !class_exists('PluginUpdate', false) ) { class PluginUpdate extends wcva_PluginUpdate_2_2 {} } if ( !class_exists('PluginInfo', false) ) { class PluginInfo extends wcva_PluginInfo_2_2 {} } /** * Check for valid envato item purchase code via envato api */
markredballoon/clivemizen
wp-content/plugins/woocommerce-colororimage-variation-select/plugin-update-checker/plugin-update-checker.php
PHP
gpl-2.0
43,682
<?php /** * Event List * * @author ProSports * @package ProSports/Templates * @version 1.5 */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly $defaults = array( 'id' => null, 'status' => 'default', 'date' => 'default', 'date_from' => 'default', 'date_to' => 'default', 'number' => -1, 'show_team_logo' => get_option( 'prosports_event_list_show_logos', 'no' ) == 'yes' ? true : false, 'link_teams' => get_option( 'prosports_link_teams', 'no' ) == 'yes' ? true : false, 'link_venues' => get_option( 'prosports_link_venues', 'yes' ) == 'yes' ? true : false, 'sortable' => get_option( 'prosports_enable_sortable_tables', 'yes' ) == 'yes' ? true : false, 'scrollable' => get_option( 'prosports_enable_scrollable_tables', 'yes' ) == 'yes' ? true : false, 'responsive' => get_option( 'prosports_enable_responsive_tables', 'yes' ) == 'yes' ? true : false, 'paginated' => get_option( 'prosports_event_list_paginated', 'yes' ) == 'yes' ? true : false, 'rows' => get_option( 'prosports_event_list_rows', 10 ), 'order' => 'default', 'columns' => null, 'show_all_events_link' => false, ); extract( $defaults, EXTR_SKIP ); $calendar = new SP_Calendar( $id ); if ( $status != 'default' ) $calendar->status = $status; if ( $date != 'default' ) $calendar->date = $date; if ( $date_from != 'default' ) $calendar->from = $date_from; if ( $date_to != 'default' ) $calendar->to = $date_to; if ( $order != 'default' ) $calendar->order = $order; $data = $calendar->data(); $usecolumns = $calendar->columns; $title_format = get_option( 'prosports_event_list_title_format', 'title' ); $time_format = get_option( 'prosports_event_list_time_format', 'combined' ); if ( isset( $columns ) ): if ( is_array( $columns ) ) $usecolumns = $columns; else $usecolumns = explode( ',', $columns ); endif; if ( $id ) { echo '<h4 class="sp-table-caption">' . get_the_title( $id ) . '</h4>'; } ?> <div class="sp-template sp-template-event-list"> <div class="sp-table-wrapper<?php if ( $scrollable ) { ?> sp-scrollable-table-wrapper<?php } ?>"> <table class="sp-event-list sp-data-table<?php if ( $responsive ) { ?> sp-responsive-table<?php } if ( $paginated ) { ?> sp-paginated-table<?php } if ( $sortable ) { ?> sp-sortable-table<?php } ?>" data-sp-rows="<?php echo $rows; ?>"> <thead> <tr> <?php echo '<th class="data-date">' . __( 'Date', 'prosports' ) . '</th>'; switch ( $title_format ) { case 'homeaway': if ( sp_column_active( $usecolumns, 'event' ) ) { echo '<th class="data-home">' . __( 'Home', 'prosports' ) . '</th>'; if ( 'combined' == $time_format && sp_column_active( $usecolumns, 'time' ) ) { echo '<th class="data-time">&nbsp;</th>'; } elseif ( in_array( $time_format, array( 'separate', 'results' ) ) && sp_column_active( $usecolumns, 'results' ) ) { echo '<th class="data-results">&nbsp;</th>'; } echo '<th class="data-away">' . __( 'Away', 'prosports' ) . '</th>'; if ( in_array( $time_format, array( 'separate', 'time' ) ) && sp_column_active( $usecolumns, 'time' ) ) { echo '<th class="data-time">' . __( 'Time', 'prosports' ) . '</th>'; } } break; default: if ( sp_column_active( $usecolumns, 'event' ) ) { if ( $title_format == 'teams' ) echo '<th class="data-teams">' . __( 'Teams', 'prosports' ) . '</th>'; else echo '<th class="data-event">' . __( 'Event', 'prosports' ) . '</th>'; } switch ( $time_format ) { case 'separate': if ( sp_column_active( $usecolumns, 'time' ) ) echo '<th class="data-time">' . __( 'Time', 'prosports' ) . '</th>'; if ( sp_column_active( $usecolumns, 'results' ) ) echo '<th class="data-results">' . __( 'Results', 'prosports' ) . '</th>'; break; case 'time': if ( sp_column_active( $usecolumns, 'time' ) ) echo '<th class="data-time">' . __( 'Time', 'prosports' ) . '</th>'; break; case 'results': if ( sp_column_active( $usecolumns, 'results' ) ) echo '<th class="data-results">' . __( 'Results', 'prosports' ) . '</th>'; break; default: if ( sp_column_active( $usecolumns, 'time' ) ) echo '<th class="data-time">' . __( 'Time/Results', 'prosports' ) . '</th>'; } } if ( sp_column_active( $usecolumns, 'league' ) ) echo '<th class="data-league">' . __( 'Competition', 'prosports' ) . '</th>'; if ( sp_column_active( $usecolumns, 'season' ) ) echo '<th class="data-season">' . __( 'Season', 'prosports' ) . '</th>'; if ( sp_column_active( $usecolumns, 'venue' ) ) echo '<th class="data-venue">' . __( 'Venue', 'prosports' ) . '</th>'; if ( sp_column_active( $usecolumns, 'article' ) ) echo '<th class="data-article">' . __( 'Article', 'prosports' ) . '</th>'; ?> </tr> </thead> <tbody> <?php $i = 0; if ( is_numeric( $number ) && $number > 0 ) $limit = $number; foreach ( $data as $event ): if ( isset( $limit ) && $i >= $limit ) continue; $teams = get_post_meta( $event->ID, 'sp_team' ); $video = get_post_meta( $event->ID, 'sp_video', true ); $main_results = sp_get_main_results( $event ); $teams_output = ''; $teams_array = array(); $team_logos = array(); if ( $teams ): foreach ( $teams as $team ): $name = get_the_title( $team ); if ( $name ): if ( $show_team_logo ): $name = sp_get_logo( $team, 'mini' ) . ' ' . $name; $team_logos[] = sp_get_logo( $team, 'mini' ); endif; if ( $link_teams ): $team_output = '<a href="' . get_post_permalink( $team ) . '">' . $name . '</a>'; else: $team_output = $name; endif; $team_result = sp_array_value( $main_results, $team, null ); if ( $team_result != null ): if ( $usecolumns != null && ! in_array( 'time', $usecolumns ) ): $team_output .= ' (' . $team_result . ')'; endif; endif; $teams_array[] = $team_output; $teams_output .= $team_output . '<br>'; endif; endforeach; else: $teams_output .= '&mdash;'; endif; echo '<tr class="sp-row sp-post' . ( $i % 2 == 0 ? ' alternate' : '' ) . '">'; echo '<td class="data-date"><a href="' . get_permalink( $event->ID ) . '"><date>' . get_post_time( 'Y-m-d H:i:s', false, $event ) . '</date>' . get_post_time( get_option( 'date_format' ), false, $event, true ) . '</a></td>'; switch ( $title_format ) { case 'homeaway': if ( sp_column_active( $usecolumns, 'event' ) ) { $team = array_shift( $teams_array ); echo '<td class="data-home">' . $team . '</td>'; if ( 'combined' == $time_format && sp_column_active( $usecolumns, 'time' ) ) { echo '<td class="data-time"><a href="' . get_permalink( $event->ID ) . '">'; if ( ! empty( $main_results ) ): echo implode( ' - ', $main_results ); else: echo '<date>&nbsp;' . get_post_time( 'H:i:s', false, $event ) . '</date>' . sp_get_time( $event ); endif; echo '</a></td>'; } elseif ( in_array( $time_format, array( 'separate', 'results' ) ) && sp_column_active( $usecolumns, 'results' ) ) { echo '<td class="data-results"><a href="' . get_permalink( $event->ID ) . '">'; if ( ! empty( $main_results ) ): echo implode( ' - ', $main_results ); else: echo '-'; endif; echo '</a></td>'; } $team = array_shift( $teams_array ); echo '<td class="data-away">' . $team . '</td>'; if ( in_array( $time_format, array( 'separate', 'time' ) ) && sp_column_active( $usecolumns, 'time' ) ) { echo '<td class="data-time"><a href="' . get_permalink( $event->ID ) . '">'; echo '<date>&nbsp;' . get_post_time( 'H:i:s', false, $event ) . '</date>' . sp_get_time( $event ); echo '</a></td>'; } } break; default: if ( sp_column_active( $usecolumns, 'event' ) ) { if ( $title_format == 'teams' ) echo '<td class="data-event data-teams">' . $teams_output . '</td>'; else echo '<td class="data-event"><a href="' . get_permalink( $event->ID ) . '">' . implode( ' ', $team_logos ) . ' ' . $event->post_title . '</a></td>'; } switch ( $time_format ) { case 'separate': if ( sp_column_active( $usecolumns, 'time' ) ) { echo '<td class="data-time"><a href="' . get_permalink( $event->ID ) . '">'; echo '<date>&nbsp;' . get_post_time( 'H:i:s', false, $event ) . '</date>' . sp_get_time( $event ); echo '</a></td>'; } if ( sp_column_active( $usecolumns, 'results' ) ) { echo '<td class="data-results"><a href="' . get_permalink( $event->ID ) . '">'; if ( ! empty( $main_results ) ): echo implode( ' - ', $main_results ); else: echo '-'; endif; echo '</a></td>'; } break; case 'time': if ( sp_column_active( $usecolumns, 'time' ) ) { echo '<td class="data-time"><a href="' . get_permalink( $event->ID ) . '">'; echo '<date>&nbsp;' . get_post_time( 'H:i:s', false, $event ) . '</date>' . sp_get_time( $event ); echo '</a></td>'; } break; case 'results': if ( sp_column_active( $usecolumns, 'results' ) ) { echo '<td class="data-results"><a href="' . get_permalink( $event->ID ) . '">'; if ( ! empty( $main_results ) ): echo implode( ' - ', $main_results ); else: echo '-'; endif; echo '</a></td>'; } break; default: if ( sp_column_active( $usecolumns, 'time' ) ) { echo '<td class="data-time"><a href="' . get_permalink( $event->ID ) . '">'; if ( ! empty( $main_results ) ): echo implode( ' - ', $main_results ); else: echo '<date>&nbsp;' . get_post_time( 'H:i:s', false, $event ) . '</date>' . sp_get_time( $event ); endif; echo '</a></td>'; } } } if ( sp_column_active( $usecolumns, 'league' ) ): echo '<td class="data-league">'; $leagues = get_the_terms( $event->ID, 'sp_league' ); if ( $leagues ): foreach ( $leagues as $league ): echo $league->name; endforeach; endif; echo '</td>'; endif; if ( sp_column_active( $usecolumns, 'season' ) ): echo '<td class="data-season">'; $seasons = get_the_terms( $event->ID, 'sp_season' ); if ( $seasons ): foreach ( $seasons as $season ): echo $season->name; endforeach; endif; echo '</td>'; endif; if ( sp_column_active( $usecolumns, 'venue' ) ): echo '<td class="data-venue">'; if ( $link_venues ): the_terms( $event->ID, 'sp_venue' ); else: $venues = get_the_terms( $event->ID, 'sp_venue' ); if ( $venues ): foreach ( $venues as $venue ): echo $venue->name; endforeach; endif; endif; echo '</td>'; endif; if ( sp_column_active( $usecolumns, 'article' ) ): echo '<td class="data-article"> <a href="' . get_permalink( $event->ID ) . '">'; if ( $video ): echo '<div class="dashicons dashicons-video-alt"></div>'; elseif ( has_post_thumbnail( $event->ID ) ): echo '<div class="dashicons dashicons-camera"></div>'; endif; if ( $event->post_content !== null ): if ( $event->post_status == 'publish' ): _e( 'Recap', 'prosports' ); else: _e( 'Preview', 'prosports' ); endif; endif; echo '</a> </td>'; endif; echo '</tr>'; $i++; endforeach; ?> </tbody> </table> </div> <?php if ( $id && $show_all_events_link ) echo '<a class="sp-calendar-link sp-view-all-link" href="' . get_permalink( $id ) . '">' . __( 'View all events', 'prosports' ) . '</a>'; ?> </div>
parpaitas1987/ProSports
sm-manager-setup/includes/prosports/templates/event-list.php
PHP
gpl-2.0
12,406
<?php $PHPMaker_vers = 'v5.0.0'; define('ADODB_FETCH_DEFAULT', 0); define('ADODB_FETCH_NUM', 1); define('ADODB_FETCH_ASSOC', 2); define('ADODB_FETCH_BOTH', 3); define("EW_USE_MYSQLI", FALSE, TRUE); $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT; // DEFAULT or BOTH. DO NOT CHANGE! /** * ADOConnection */ class ADOConnection { var $connectionId = false; var $record_set = false; var $database; var $dbtype; var $dataProvider; var $host; var $open; var $password; var $username; var $persistent; var $debug = false; var $debug_console = false; var $debug_echo = true; var $debug_output; var $forcenewconnection = false; var $createdatabase = false; var $last_module_name; var $socket = false; var $port = false; var $clientFlags = 0; var $nameQuote = '"'; var $sysDate = false; /// name of function that returns the current date var $sysTimeStamp = false; /// name of function that returns the current timestamp var $sql; var $raiseErrorFn = false; var $query_count = 0; var $query_time_total = 0; var $query_list = array(); var $query_list_time = array(); var $query_list_errors = array(); var $_logsql = false; function ADOConnection() { } /** * @access public */ function Version() { global $PHPMaker_vers; return (float) substr($PHPMaker_vers,1); } /** * Returns true if connected to database * Usage: $db->IsConnected(); * * @access public */ function IsConnected() { if($this->connectionId === false || $this->connectionId == false) return false; else return true; } /** * Normal Database connection * Usage: $result = $db->Connect('host', 'username', 'password', 'database'); * * @access public * @param string $database * @param string $host * @param string $password * @param string $username * @param string $forcenew // private */ function Connect( $host = "", $username = "", $password = "", $database = "", $forcenew = false) { return $this->_connect($host, $username, $password, $database, false, $forcenew); } /** * Persistent Database connection * Usage: $result = $db->PConnect('host', 'username', 'password', 'database'); * * @access public * @param string $database * @param string $host * @param string $password * @param string $username */ function PConnect( $host = "", $username = "", $password = "", $database = "") { return $this->_connect($host, $username, $password, $database, true, false); } /** * Force New Database connection * Usage: $result = $db->NConnect('host', 'username', 'password', 'database'); * * @access public * @param string $database * @param string $host * @param string $password * @param string $username */ function NConnect( $host = "", $username = "", $password = "", $database = "") { return $this->_connect($host, $username, $password, $database, false, true); } /** * Returns SQL query and instantiates sql statement & resultset driver * Usage: $linkId =& $db->execute( 'SELECT * FROM foo ORDER BY id' ); * * @access public * @param string $sql * @return mixed Resource ID, Array */ function &Execute( $sql, $inputarr = false ) { // adodb_log_sql will time the query execution and log the sql query // note: the later $this->do_query() should not run since adodb_log_sql() independently executes the query itself. if($this->_logsql === true) { $ret =& adodb_log_sql($this, $sql, $inputarr); if (isset($ret)) return $ret; } $rs =& $this->do_query($sql, -1, -1, $inputarr); return $rs; } /** * Returns SQL query and instantiates sql statement & resultset driver * Usage: $linkId =& $db->SelectLimit( 'SELECT * FROM foo ORDER BY id', $nrows, $offset ); * $nrows and $offset are optional * * @access public * @param string $sql * @param string $nrows * @param string $offset * @return mixed Resource ID, Array */ function &SelectLimit( $sql, $nrows=-1, $offset=-1, $inputarr=false, $secs2cache=0 ) { $rs =& $this->do_query( $sql, $offset, $nrows, $inputarr); return $rs; } /** * Display debug output and database error. * * @access private */ function outp($text, $newline = true) { global $ADODB_OUTP; $this->debug_output = "<br>\n(" . $this->dbtype . "): ".htmlspecialchars($text)."<br>\n Error (" . $this->ErrorNo() .'): '. $this->ErrorMsg() . "<br>\n"; if(defined('ADODB_OUTP')) { $fn = ADODB_OUTP; } else if(isset($ADODB_OUTP)) { $fn = $ADODB_OUTP; } if(defined('ADODB_OUTP') || isset($ADODB_OUTP)) { $fn($this->debug_output, $newline); return; } if($this->debug_echo) echo $this->debug_output; } } /** * Empty result record set for updates, inserts, ect * * @access private */ class ADORecordSet_empty { var $fields = false; var $EOF = true; function MoveNext() {return;} function RecordCount() {return 0;} function FieldCount() {return 0;} function EOF(){return TRUE;} function Close(){return true;} } /** * mysqlt_driver_ADOConnection */ class mysqlt_driver_ADOConnection extends ADOConnection { var $autoCommit = true; var $transOff = 0; var $transCnt = 0; var $transaction_status = true; var $nameQuote = '`'; var $sysDate = 'CURDATE()'; var $sysTimeStamp = 'NOW()'; var $isoDates = true; // accepts dates in ISO format function mysqlt_driver_ADOConnection() { $this->dbtype = 'mysqlt'; $this->dataProvider = 'mysql'; $this->last_module_name = 'mysqlt_driver'; } /** * Connection to database server and selected database * * @access private */ function _connect($host = "", $username = "", $password = "", $database = "", $persistent, $forcenew) { if (EW_USE_MYSQLI) { if (!function_exists('mysqli_real_connect')) return false; $this->host = $host; $this->username = $username; $this->password = $password; $this->database = $database; $this->persistent = $persistent; $this->forcenewconnection = $forcenew; $this->connectionId = @mysqli_init(); @mysqli_real_connect( $this->connectionId, $this->host, $this->username, $this->password, $this->database, $this->port, $this->socket, $this->clientFlags ); if (mysqli_connect_errno() != 0) { $this->connectionId = false; } } else { if (!function_exists('mysql_connect')) return false; $this->host = $host; if (!empty($this->port)) $this->host .= ":" . $this->port; $this->username = $username; $this->password = $password; $this->database = $database; $this->persistent = $persistent; $this->forcenewconnection = $forcenew; if($this->persistent == 1) { if (strnatcmp(PHP_VERSION, '4.3.0') >= 0) $this->connectionId = @mysql_pconnect( $this->host, $this->username, $this->password, $this->clientFlags ); else $this->connectionId = @mysql_pconnect( $this->host, $this->username, $this->password ); } else { if (strnatcmp(PHP_VERSION, '4.3.0') >= 0) $this->connectionId = @mysql_connect( $this->host, $this->username, $this->password, $this->forcenewconnection, $this->clientFlags ); else if (strnatcmp(PHP_VERSION, '4.2.0') >= 0) $this->connectionId = @mysql_connect( $this->host, $this->username, $this->password, $this->forcenewconnection ); else $this->connectionId = @mysql_connect( $this->host, $this->username, $this->password ); } } if ($this->connectionId === false) { if ($fn = $this->raiseErrorFn) $fn($this->dbtype, 'CONNECT', $this->ErrorNo(), $this->ErrorMsg(), $this->host, $this->database, $this); return false; } if (!empty($this->database)) { if($this->SelectDB( $this->database ) == false) { $this->connectionId = false; return false; } } return true; } /** * Choose a database to connect. * * @param dbname is the name of the database to select * @return true or false * @access public */ function SelectDB($dbname) { $this->database = $dbname; if ($this->connectionId === false) { $this->connectionId = false; return false; } else { if (EW_USE_MYSQLI) { $result = @mysqli_select_db( $this->connectionId, $this->database ); } else { $result = @mysql_select_db( $this->database, $this->connectionId ); } if($result === false) { if($this->createdatabase == true) { if (EW_USE_MYSQLI) { $result = @mysqli_query( $this->connectionId, "CREATE DATABASE IF NOT EXISTS " . $this->database ); } else { $result = @mysql_query( "CREATE DATABASE IF NOT EXISTS " . $this->database, $this->connectionId ); } if ($result === false) { // error handling if query fails return false; } if (EW_USE_MYSQLI) { $result = @mysqli_select_db( $this->connectionId, $this->database ); } else { $result = @mysql_select_db( $this->database, $this->connectionId ); } if($result === false) { return false; } } else { return false; } } return true; } } /** * Return database error message * Usage: $errormessage =& $db->ErrorMsg(); * * @access public */ function ErrorMsg() { if ($this->connectionId === false) { if (EW_USE_MYSQLI) { return @mysqli_connect_error(); } else { return @mysql_error(); } } else { if (EW_USE_MYSQLI) { return @mysqli_error($this->connectionId); } else { return @mysql_error($this->connectionId); } } } /** * Return database error number * Usage: $errorbo =& $db->ErrorNo(); * * @access public */ function ErrorNo() { if ($this->connectionId === false) { if (EW_USE_MYSQLI) { return @mysqli_connect_errno(); } else { return @mysql_errno(); } } else { if (EW_USE_MYSQLI) { return @mysqli_errno($this->connectionId); } else { return @mysql_errno($this->connectionId); } } } /** * Returns # of affected rows from insert/delete/update query * * @access public * @return integer Affected rows */ function Affected_Rows() { if (EW_USE_MYSQLI) { return @mysqli_affected_rows($this->connectionId); } else { return @mysql_affected_rows($this->connectionId); } } /** * Returns the last record id of an inserted item * Usage: $db->Insert_ID(); * * @access public */ function Insert_ID() { if (EW_USE_MYSQLI) { return @mysqli_insert_id($this->connectionId); } else { return @mysql_insert_id($this->connectionId); } } /** * Correctly quotes a string so that all strings are escape coded. * An example is $db->qstr("Haven't a clue."); * * @param string the string to quote * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc(). * * @return single-quoted string IE: 'Haven\'t a clue.' */ function qstr($string, $magic_quotes=false) { if (!$magic_quotes) { if (EW_USE_MYSQLI) { if (strnatcmp(PHP_VERSION, '4.3.0') >= 0 && function_exists('mysqli_real_escape_string')) { return "'" . mysqli_real_escape_string($this->connectionId, $string) . "'"; } } else { if (strnatcmp(PHP_VERSION, '4.3.0') >= 0) { return "'" . mysql_real_escape_string($string, $this->connectionId) . "'"; } } $string = str_replace("'", "\\'" , str_replace('\\', '\\\\', str_replace("\0", "\\\0", $string))); return "'" . $string . "'"; } return "'" . str_replace('\\"', '"', $string) . "'"; } function QMagic($string) { return $this->qstr($string, get_magic_quotes_gpc()); } /** * Returns concatenated string * Usage: $db->Concat($str1,$str2); * * @return concatenated string */ function Concat() { $arr = func_get_args(); $list = implode(', ', $arr); if (strlen($list) > 0) return "CONCAT($list)"; else return ''; } function IfNull( $field, $ifNull ) { return " IFNULL($field, $ifNull) "; } /** * Closes database connection * Usage: $db->close(); * * @access public */ function Close() { if (EW_USE_MYSQLI) { @mysqli_close( $this->connectionId ); } else { @mysql_close( $this->connectionId ); } $this->connectionId = false; } function StartTrans($errfn = 'ADODB_TransMonitor') { if ($this->transOff > 0) { $this->transOff += 1; return; } $this->transaction_status = true; if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans"); $this->BeginTrans(); $this->transOff = 1; } function BeginTrans() { if ($this->transOff) return true; $this->transCnt += 1; $this->Execute('SET AUTOCOMMIT=0'); $this->Execute('BEGIN'); return true; } function CompleteTrans($autoComplete = true) { if ($this->transOff > 1) { $this->transOff -= 1; return true; } $this->transOff = 0; if ($this->transaction_status && $autoComplete) { if (!$this->CommitTrans()) { $this->transaction_status = false; if ($this->debug) ADOConnection::outp("Smart Commit failed"); } else if ($this->debug) ADOConnection::outp("Smart Commit occurred"); } else { $this->RollbackTrans(); if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred"); } return $this->transaction_status; } function CommitTrans($ok=true) { if ($this->transOff) return true; if (!$ok) return $this->RollbackTrans(); if ($this->transCnt) $this->transCnt -= 1; $this->Execute('COMMIT'); $this->Execute('SET AUTOCOMMIT=1'); return true; } function RollbackTrans() { if ($this->transOff) return true; if ($this->transCnt) $this->transCnt -= 1; $this->Execute('ROLLBACK'); $this->Execute('SET AUTOCOMMIT=1'); return true; } function FailTrans() { if ($this->debug) if ($this->transOff == 0) { ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans"); } else { ADOConnection::outp("FailTrans was called"); } $this->transaction_status = false; } function HasFailedTrans() { if ($this->transOff > 0) return $this->transaction_status == false; return false; } function RowLock($tables,$where,$flds='1 as ignore') { if ($this->transCnt==0) $this->BeginTrans(); return $this->GetOne("select $flds from $tables where $where for update"); } function CommitLock($table) { return $this->CommitTrans(); } function RollbackLock($table) { return $this->RollbackTrans(); } /** * Returns All Records in an array * * Usage: $db->GetAll($sql); * @access public */ function &GetAll($sql, $inputarr = false) { $data =& $this->GetArray($sql, $inputarr); return $data; } /** * Returns All Records in an array * * Usage: $db->GetArray($sql); * @access public */ function &GetArray($sql, $inputarr = false) { $data = false; $result =& $this->Execute($sql, $inputarr); if ($result) { $data =& $result->GetArray(); $result->Close(); } return $data; } /** * Executes SQL query and instantiates resultset methods * * @access private * @return mixed Resultset methods */ function &do_query( $sql, $offset, $nrows, $inputarr=false ) { global $ADODB_FETCH_MODE; $false = false; $limit = ''; if ($offset >= 0 || $nrows >= 0) { $offset = ($offset >= 0) ? $offset . "," : ''; $nrows = ($nrows >= 0) ? $nrows : '18446744073709551615'; $limit = ' LIMIT ' . $offset . ' ' . $nrows; } if ($inputarr && is_array($inputarr)) { $sqlarr = explode('?', $sql); if (!is_array(reset($inputarr))) $inputarr = array($inputarr); foreach($inputarr as $arr) { $sql = ''; $i = 0; foreach($arr as $v) { $sql .= $sqlarr[$i]; switch(gettype($v)){ case 'string': $sql .= $this->qstr($v); break; case 'double': $sql .= str_replace(',', '.', $v); break; case 'boolean': $sql .= $v ? 1 : 0; break; default: if ($v === null) $sql .= 'NULL'; else $sql .= $v; } $i += 1; } $sql .= $sqlarr[$i]; if ($i+1 != sizeof($sqlarr)) return $false; $this->sql = $sql . $limit; $time_start = array_sum(explode(' ', microtime())); $this->query_count++; if (EW_USE_MYSQLI) { $resultId = @mysqli_query($this->connectionId, $this->sql ); } else { $resultId = @mysql_query( $this->sql, $this->connectionId ); } $time_total = (array_sum(explode(' ', microtime())) - $time_start); $this->query_time_total += $time_total; if($this->debug_console) { $this->query_list[] = $this->sql; $this->query_list_time[] = $time_total; $this->query_list_errors[] = $this->ErrorMsg(); } if($this->debug) { $this->outp($sql . $limit); } } } else { $this->sql = $sql . $limit; $time_start = array_sum(explode(' ', microtime())); $this->query_count++; if (EW_USE_MYSQLI) { $resultId = @mysqli_query($this->connectionId, $this->sql ); } else { $resultId = @mysql_query( $this->sql, $this->connectionId ); } $time_total = (array_sum(explode(' ', microtime())) - $time_start); $this->query_time_total += $time_total; if($this->debug_console) { $this->query_list[] = $this->sql; $this->query_list_time[] = $time_total; $this->query_list_errors[] = $this->ErrorMsg(); } if($this->debug) { $this->outp($sql . $limit); } } if ($resultId === false) { // error handling if query fails if ($fn = $this->raiseErrorFn) $fn($this->dbtype, 'EXECUTE', $this->ErrorNo(), $this->ErrorMsg(), $this->sql, $inputarr, $this); return $false; } if ($resultId === true) { // return simplified recordset for inserts/updates/deletes with lower overhead $recordset = new ADORecordSet_empty(); return $recordset; } $resultset_name = $this->last_module_name . "_ResultSet"; $recordset = new $resultset_name( $resultId, $this->connectionId ); $recordset->_currentRow = 0; if (EW_USE_MYSQLI) { switch ($ADODB_FETCH_MODE) { case ADODB_FETCH_NUM: $recordset->fetchMode = MYSQLI_NUM; break; case ADODB_FETCH_ASSOC:$recordset->fetchMode = MYSQLI_ASSOC; break; default: case ADODB_FETCH_DEFAULT: case ADODB_FETCH_BOTH:$recordset->fetchMode = MYSQLI_BOTH; break; } } else { switch ($ADODB_FETCH_MODE) { case ADODB_FETCH_NUM: $recordset->fetchMode = MYSQL_NUM; break; case ADODB_FETCH_ASSOC:$recordset->fetchMode = MYSQL_ASSOC; break; default: case ADODB_FETCH_DEFAULT: case ADODB_FETCH_BOTH:$recordset->fetchMode = MYSQL_BOTH; break; } } if (EW_USE_MYSQLI) { $recordset->_numOfRows = @mysqli_num_rows( $resultId ); } else { $recordset->_numOfRows = @mysql_num_rows( $resultId ); } if( $recordset->_numOfRows == 0) { $recordset->EOF = true; } if (EW_USE_MYSQLI) { $recordset->_numOfFields = @mysqli_num_fields( $resultId ); } else { $recordset->_numOfFields = @mysql_num_fields( $resultId ); } $recordset->_fetch(); return $recordset; } } class mysqlt_driver_ResultSet { var $connectionId; var $fields; var $resultId; var $_currentRow = 0; var $_numOfRows = -1; var $_numOfFields = -1; var $fetchMode; var $EOF; /** * mysqlResultSet Constructor * * @access private * @param string $record * @param string $resultId */ function mysqlt_driver_ResultSet( $resultId, $connectionId ) { $this->fields = array(); $this->connectionId = $connectionId; $this->record = array(); $this->resultId = $resultId; $this->EOF = false; } /** * Frees resultset * * @access public */ function Close() { if (EW_USE_MYSQLI) { @mysqli_free_result( $this->resultId ); } else { @mysql_free_result( $this->resultId ); } $this->fields = array(); $this->resultId = false; } /** * Returns field name from select query * * @access public * @param string $field * @return string Field name */ function fields( $field ) { if(empty($field)) { return $this->fields; } else { return $this->fields[$field]; } } /** * Returns numrows from select query * * @access public * @return integer Numrows */ function RecordCount() { return $this->_numOfRows; } /** * Returns num of fields from select query * * @access public * @return integer numfields */ function FieldCount() { return $this->_numOfFields; } /** * Returns next record * * @access public */ function MoveNext() { if (EW_USE_MYSQLI) { $this->fields = @mysqli_fetch_array($this->resultId,$this->fetchMode); } else { $this->fields = @mysql_fetch_array($this->resultId, $this->fetchMode); } if ($this->fields) { $this->_currentRow += 1; return true; } if (!$this->EOF) { $this->_currentRow += 1; $this->EOF = true; } return false; } /** * Move to the first row in the recordset. Many databases do NOT support this. * * @return true or false */ function MoveFirst() { if ($this->_currentRow == 0) return true; return $this->Move(0); } /** * Returns the Last Record * * @access public */ function MoveLast() { if ($this->EOF) return false; return $this->Move($this->_numOfRows - 1); } /** * Random access to a specific row in the recordset. Some databases do not support * access to previous rows in the databases (no scrolling backwards). * * @param rowNumber is the row to move to (0-based) * * @return true if there still rows available, or false if there are no more rows (EOF). */ function Move($rowNumber = 0) { if ($rowNumber == $this->_currentRow) return true; $this->EOF = false; if ($this->_numOfRows > 0){ if ($rowNumber >= $this->_numOfRows - 1){ $rowNumber = $this->_numOfRows - 1; } } if ($this->_seek($rowNumber)) { $this->_currentRow = $rowNumber; if ($this->_fetch()) { return true; } $this->fields = false; } $this->EOF = true; return false; } /** * Perform Seek to specific row * * @access private */ function _seek($row) { if ($this->_numOfRows == 0) return false; if (EW_USE_MYSQLI) { return @mysqli_data_seek($this->resultId,$row); } else { return @mysql_data_seek($this->resultId,$row); } } /** * Fills field array with first database element when query initially executed * * @access private */ function _fetch() { if (EW_USE_MYSQLI) { $this->fields = @mysqli_fetch_array($this->resultId,$this->fetchMode); } else { $this->fields = @mysql_fetch_array($this->resultId,$this->fetchMode); } return is_array($this->fields); } /** * Check to see if last record reached * * @access public */ function EOF() { if( $this->_currentRow < $this->_numOfRows) { return false; } else { $this->EOF = true; return true; } } /** * Returns All Records in an array * * @access public * @param [nRows] is the number of rows to return. -1 means every row. */ function &GetArray($nRows = -1) { $results = array(); $cnt = 0; while (!$this->EOF && $nRows != $cnt) { $results[] = $this->fields; $this->MoveNext(); $cnt++; } return $results; } function &GetRows($nRows = -1) { $arr =& $this->GetArray($nRows); return $arr; } function &GetAll($nRows = -1) { $arr =& $this->GetArray($nRows); return $arr; } /** * Fetch field information for a table. * * @return object containing the name, type and max_length */ function FetchField($fieldOffset = -1) { if (EW_USE_MYSQLI) { // $fieldOffset not supported by mysqli $fieldObject = @mysqli_fetch_field($this->resultId); } else { if ($fieldOffset != -1) { $fieldObject = @mysql_fetch_field($this->resultId, $fieldOffset); $fieldObject->max_length = @mysql_field_len($this->resultId,$fieldOffset); } else { $fieldObject = @mysql_fetch_field($this->resultId); $fieldObject->max_length = @mysql_field_len($this->resultId); } } return $fieldObject; } } ?>
xavierrivas/new
epcst/instructor/ewmysql50.php
PHP
gpl-2.0
23,968
package JTalk.util; public class CPLoginReq extends ClientPackage{ public int id; public String password; public int port; public CPLoginReq(int id, String password,int port){ super.type=1; this.id=id; this.password=password; this.port=port; }; }
zyclincoln/JTalk
src/JTalk/util/CPLoginReq.java
Java
gpl-2.0
261
<?php //Add Vendor if ( !empty($_POST['add_vendor']) && !empty($_POST['vname']) ) { $mysql_q="INSERT INTO vendors (vendor_id, vendor_name, vendor_phone, vendor_fax, vendor_email, vendor_details ) VALUES ( '', '".$_POST['vname']."', '".$_POST['vphone']."', '".$_POST['vfax']."', '".$_POST['vemail']."', '".$_POST['vdetail']."' )"; $dbhi->query($mysql_q); if ( $dbhi->affected_rows == 1 ) header("Location: " . $_SERVER['PHP_SELF'] . "?success=yes&message=Vendor Added"); else header("Location: " . $_SERVER['PHP_SELF'] . "?success=no&message=MYSQL ERR" . mysql_errno() ); } ?> <script> //Add Vendor popup $(function() { $( "#div_add_v" ).dialog( { autoOpen: false, height: 370, width: 500, modal: true, position: ['middle',20], close: function() { } }); }); $(document).on('click', '#b_add_v', function() { $('#div_add_v').dialog( "open" ); }); </script> <button style="margin: 10px; font-weight:bold; background-color:white;" id="b_add_v">Add Vendor</button> <div id="div_add_v" style='display:none' title="Add Vendor"> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <table> <tr> <td> <label for="vname">Vendor Name:</label> </td> <td> <input type=text name="vname" id="vname" size=30 required> </td> </tr> <tr> <td> <label for="vphone">Vendor Phone:</label> </td> <td> <input type=text name="vphone" id="vphone" size=30> </td> </tr> <tr> <td> <label for="vfax">Vendor Fax:</label> </td> <td> <input type=text name="vfax" id="vfax" size=30> </td> </tr> <tr> <td> <label for="vemail">Vendor Email:</label> </td> <td> <input type=text name="vemail" id="vemail" size=30> </td> </tr> <tr> <td> <label for="vdetail">Vendor Details:</label> </td> <td> <textarea name="vdetail" id="vdetail" rows=2 cols=24 ></textarea> </td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" name="add_vendor" value="Add Vendor" /> </td> </tr> </table> </form> </div>
kxr/stock3
include/add_vendor.php
PHP
gpl-2.0
2,210
/* $Id$ */ /* * This file is part of OpenTTD. * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2. * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>. */ /** @file dropdown.cpp Implementation of the dropdown widget. */ #include "../stdafx.h" #include "../window_gui.h" #include "../string_func.h" #include "../strings_func.h" #include "../window_func.h" #include "dropdown_type.h" #include "dropdown_widget.h" void DropDownListItem::Draw(int left, int right, int top, int bottom, bool sel, int bg_colour) const { int c1 = _colour_gradient[bg_colour][3]; int c2 = _colour_gradient[bg_colour][7]; int mid = top + this->Height(0) / 2; GfxFillRect(left + 1, mid - 2, right - 1, mid - 2, c1); GfxFillRect(left + 1, mid - 1, right - 1, mid - 1, c2); } uint DropDownListStringItem::Width() const { char buffer[512]; GetString(buffer, this->String(), lastof(buffer)); return GetStringBoundingBox(buffer).width; } void DropDownListStringItem::Draw(int left, int right, int top, int bottom, bool sel, int bg_colour) const { DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, top, this->String(), sel ? TC_WHITE : TC_BLACK); } /** * Natural sorting comparator function for DropDownList::sort(). * @param first Left side of comparison. * @param second Right side of comparison. * @return true if \a first precedes \a second. * @warning All items in the list need to be derivates of DropDownListStringItem. */ /* static */ bool DropDownListStringItem::NatSortFunc(const DropDownListItem *first, const DropDownListItem *second) { char buffer1[512], buffer2[512]; GetString(buffer1, static_cast<const DropDownListStringItem*>(first)->String(), lastof(buffer1)); GetString(buffer2, static_cast<const DropDownListStringItem*>(second)->String(), lastof(buffer2)); return strnatcmp(buffer1, buffer2) < 0; } StringID DropDownListParamStringItem::String() const { for (uint i = 0; i < lengthof(this->decode_params); i++) SetDParam(i, this->decode_params[i]); return this->string; } StringID DropDownListCharStringItem::String() const { SetDParamStr(0, this->raw_string); return this->string; } /** * Delete all items of a drop down list and the list itself * @param list List to delete. */ static void DeleteDropDownList(DropDownList *list) { for (DropDownList::iterator it = list->begin(); it != list->end(); ++it) { DropDownListItem *item = *it; delete item; } delete list; } static const NWidgetPart _nested_dropdown_menu_widgets[] = { NWidget(NWID_HORIZONTAL), NWidget(WWT_PANEL, COLOUR_END, WID_DM_ITEMS), SetMinimalSize(1, 1), SetScrollbar(WID_DM_SCROLL), EndContainer(), NWidget(NWID_SELECTION, INVALID_COLOUR, WID_DM_SHOW_SCROLL), NWidget(NWID_VSCROLLBAR, COLOUR_END, WID_DM_SCROLL), EndContainer(), EndContainer(), }; const WindowDesc _dropdown_desc( WDP_MANUAL, 0, 0, WC_DROPDOWN_MENU, WC_NONE, 0, _nested_dropdown_menu_widgets, lengthof(_nested_dropdown_menu_widgets) ); /** Drop-down menu window */ struct DropdownWindow : Window { WindowClass parent_wnd_class; ///< Parent window class. WindowNumber parent_wnd_num; ///< Parent window number. byte parent_button; ///< Parent widget number where the window is dropped from. DropDownList *list; ///< List with dropdown menu items. int selected_index; ///< Index of the selected item in the list. byte click_delay; ///< Timer to delay selection. bool drag_mode; bool instant_close; ///< Close the window when the mouse button is raised. int scrolling; ///< If non-zero, auto-scroll the item list (one time). Point position; ///< Position of the topleft corner of the window. Scrollbar *vscroll; /** * Create a dropdown menu. * @param parent Parent window. * @param list Dropdown item list. * @param selected Index of the selected item in the list. * @param button Widget of the parent window doing the dropdown. * @param instant_close Close the window when the mouse button is raised. * @param position Topleft position of the dropdown menu window. * @param size Size of the dropdown menu window. * @param wi_colour Colour of the parent widget. * @param scroll Dropdown menu has a scrollbar. * @param widget Widgets of the dropdown menu window. */ DropdownWindow(Window *parent, DropDownList *list, int selected, int button, bool instant_close, const Point &position, const Dimension &size, Colours wi_colour, bool scroll) : Window() { this->position = position; this->CreateNestedTree(&_dropdown_desc); this->vscroll = this->GetScrollbar(WID_DM_SCROLL); uint items_width = size.width - (scroll ? NWidgetScrollbar::GetVerticalDimension().width : 0); NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_DM_ITEMS); nwi->SetMinimalSize(items_width, size.height + 4); nwi->colour = wi_colour; nwi = this->GetWidget<NWidgetCore>(WID_DM_SCROLL); nwi->colour = wi_colour; this->GetWidget<NWidgetStacked>(WID_DM_SHOW_SCROLL)->SetDisplayedPlane(scroll ? 0 : SZSP_NONE); this->FinishInitNested(&_dropdown_desc, 0); CLRBITS(this->flags, WF_WHITE_BORDER); /* Total length of list */ int list_height = 0; for (DropDownList::const_iterator it = list->begin(); it != list->end(); ++it) { DropDownListItem *item = *it; list_height += item->Height(items_width); } /* Capacity is the average number of items visible */ this->vscroll->SetCapacity(size.height * (uint16)list->size() / list_height); this->vscroll->SetCount((uint16)list->size()); this->parent_wnd_class = parent->window_class; this->parent_wnd_num = parent->window_number; this->parent_button = button; this->list = list; this->selected_index = selected; this->click_delay = 0; this->drag_mode = true; this->instant_close = instant_close; } ~DropdownWindow() { Window *w2 = FindWindowById(this->parent_wnd_class, this->parent_wnd_num); if (w2 != NULL) { if (w2->nested_array != NULL) { NWidgetCore *nwi2 = w2->GetWidget<NWidgetCore>(this->parent_button); if (nwi2->type == NWID_BUTTON_DROPDOWN) { nwi2->disp_flags &= ~ND_DROPDOWN_ACTIVE; } else { w2->RaiseWidget(this->parent_button); } } else { w2->RaiseWidget(this->parent_button); } w2->SetWidgetDirty(this->parent_button); } DeleteDropDownList(this->list); } virtual Point OnInitialPosition(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number) { return this->position; } /** * Find the dropdown item under the cursor. * @param value [out] Selected item, if function returns \c true. * @return Cursor points to a dropdown item. */ bool GetDropDownItem(int &value) { if (GetWidgetFromPos(this, _cursor.pos.x - this->left, _cursor.pos.y - this->top) < 0) return false; NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_DM_ITEMS); int y = _cursor.pos.y - this->top - nwi->pos_y - 2; int width = nwi->current_x - 4; int pos = this->vscroll->GetPosition(); const DropDownList *list = this->list; for (DropDownList::const_iterator it = list->begin(); it != list->end(); ++it) { /* Skip items that are scrolled up */ if (--pos >= 0) continue; const DropDownListItem *item = *it; int item_height = item->Height(width); if (y < item_height) { if (item->masked || !item->Selectable()) return false; value = item->result; return true; } y -= item_height; } return false; } virtual void DrawWidget(const Rect &r, int widget) const { if (widget != WID_DM_ITEMS) return; TextColour colour = (TextColour)this->GetWidget<NWidgetCore>(widget)->colour; int y = r.top + 2; int pos = this->vscroll->GetPosition(); for (DropDownList::const_iterator it = this->list->begin(); it != this->list->end(); ++it) { const DropDownListItem *item = *it; int item_height = item->Height(r.right - r.left + 1); /* Skip items that are scrolled up */ if (--pos >= 0) continue; if (y + item_height < r.bottom) { bool selected = (this->selected_index == item->result); if (selected) GfxFillRect(r.left + 2, y, r.right - 1, y + item_height - 1, PC_BLACK); item->Draw(r.left, r.right, y, y + item_height, selected, colour); if (item->masked) { GfxFillRect(r.left + 1, y, r.right - 1, y + item_height - 1, _colour_gradient[colour][5], FILLRECT_CHECKER); } } y += item_height; } } virtual void OnClick(Point pt, int widget, int click_count) { if (widget != WID_DM_ITEMS) return; int item; if (this->GetDropDownItem(item)) { this->click_delay = 4; this->selected_index = item; this->SetDirty(); } } virtual void OnTick() { if (this->scrolling != 0) { int pos = this->vscroll->GetPosition(); this->vscroll->UpdatePosition(this->scrolling); this->scrolling = 0; if (pos != this->vscroll->GetPosition()) { this->SetDirty(); } } } virtual void OnMouseLoop() { Window *w2 = FindWindowById(this->parent_wnd_class, this->parent_wnd_num); if (w2 == NULL) { delete this; return; } if (this->click_delay != 0 && --this->click_delay == 0) { /* Make the dropdown "invisible", so it doesn't affect new window placement. * Also mark it dirty in case the callback deals with the screen. (e.g. screenshots). */ this->window_class = WC_INVALID; this->SetDirty(); w2->OnDropdownSelect(this->parent_button, this->selected_index); delete this; return; } if (this->drag_mode) { int item; if (!_left_button_clicked) { this->drag_mode = false; if (!this->GetDropDownItem(item)) { if (this->instant_close) { /* Make the dropdown "invisible", so it doesn't affect new window placement. * Also mark it dirty in case the callback deals with the screen. (e.g. screenshots). */ this->window_class = WC_INVALID; this->SetDirty(); if (GetWidgetFromPos(w2, _cursor.pos.x - w2->left, _cursor.pos.y - w2->top) == this->parent_button) { /* Send event for selected option if we're still * on the parent button of the list. */ w2->OnDropdownSelect(this->parent_button, this->selected_index); } delete this; } return; } this->click_delay = 2; } else { if (_cursor.pos.y <= this->top + 2) { /* Cursor is above the list, set scroll up */ this->scrolling = -1; return; } else if (_cursor.pos.y >= this->top + this->height - 2) { /* Cursor is below list, set scroll down */ this->scrolling = 1; return; } if (!this->GetDropDownItem(item)) return; } if (this->selected_index != item) { this->selected_index = item; this->SetDirty(); } } } }; void ShowDropDownList(Window *w, DropDownList *list, int selected, int button, uint width, bool auto_width, bool instant_close) { DeleteWindowById(WC_DROPDOWN_MENU, 0); /* Our parent's button widget is used to determine where to place the drop * down list window. */ Rect wi_rect; Colours wi_colour; NWidgetCore *nwi = w->GetWidget<NWidgetCore>(button); wi_rect.left = nwi->pos_x; wi_rect.right = nwi->pos_x + nwi->current_x - 1; wi_rect.top = nwi->pos_y; wi_rect.bottom = nwi->pos_y + nwi->current_y - 1; wi_colour = nwi->colour; if (nwi->type == NWID_BUTTON_DROPDOWN) { nwi->disp_flags |= ND_DROPDOWN_ACTIVE; } else { w->LowerWidget(button); } w->SetWidgetDirty(button); /* The preferred position is just below the dropdown calling widget */ int top = w->top + wi_rect.bottom + 1; if (width == 0) width = wi_rect.right - wi_rect.left + 1; uint max_item_width = 0; if (auto_width) { /* Find the longest item in the list */ for (DropDownList::const_iterator it = list->begin(); it != list->end(); ++it) { const DropDownListItem *item = *it; max_item_width = max(max_item_width, item->Width() + 5); } } /* Total length of list */ int list_height = 0; for (DropDownList::const_iterator it = list->begin(); it != list->end(); ++it) { DropDownListItem *item = *it; list_height += item->Height(width); } /* Height of window visible */ int height = list_height; /* Check if the status bar is visible, as we don't want to draw over it */ int screen_bottom = GetMainViewBottom(); bool scroll = false; /* Check if the dropdown will fully fit below the widget */ if (top + height + 4 >= screen_bottom) { /* If not, check if it will fit above the widget */ if (w->top + wi_rect.top - height > GetMainViewTop()) { top = w->top + wi_rect.top - height - 4; } else { /* ... and lastly if it won't, enable the scroll bar and fit the * list in below the widget */ int avg_height = list_height / (int)list->size(); int rows = (screen_bottom - 4 - top) / avg_height; height = rows * avg_height; scroll = true; /* Add space for the scroll bar if we automatically determined * the width of the list. */ max_item_width += NWidgetScrollbar::GetVerticalDimension().width; } } if (auto_width) width = max(width, max_item_width); Point dw_pos = { w->left + (_current_text_dir == TD_RTL ? wi_rect.right + 1 - width : wi_rect.left), top}; Dimension dw_size = {width, height}; new DropdownWindow(w, list, selected, button, instant_close, dw_pos, dw_size, wi_colour, scroll); } /** * Show a dropdown menu window near a widget of the parent window. * The result code of the items is their index in the \a strings list. * @param w Parent window that wants the dropdown menu. * @param strings Menu list, end with #INVALID_STRING_ID * @param selected Index of initial selected item. * @param button Button widget number of the parent window \a w that wants the dropdown menu. * @param disabled_mask Bitmask for diabled items (items with their bit set are not copied to the dropdown list). * @param hidden_mask Bitmask for hidden items (items with their bit set are displayed, but not selectable in the dropdown list). * @param width Width of the dropdown menu. If \c 0, use the width of parent widget \a button. */ void ShowDropDownMenu(Window *w, const StringID *strings, int selected, int button, uint32 disabled_mask, uint32 hidden_mask, uint width) { DropDownList *list = new DropDownList(); for (uint i = 0; strings[i] != INVALID_STRING_ID; i++) { if (!HasBit(hidden_mask, i)) { list->push_back(new DropDownListStringItem(strings[i], i, HasBit(disabled_mask, i))); } } /* No entries in the list? */ if (list->size() == 0) { DeleteDropDownList(list); return; } ShowDropDownList(w, list, selected, button, width); } /** * Delete the drop-down menu from window \a pw * @param pw Parent window of the drop-down menu window * @return Parent widget number if the drop-down was found and closed, \c -1 if the window was not found. */ int HideDropDownMenu(Window *pw) { Window *w; FOR_ALL_WINDOWS_FROM_BACK(w) { if (w->window_class != WC_DROPDOWN_MENU) continue; DropdownWindow *dw = dynamic_cast<DropdownWindow*>(w); if (pw->window_class == dw->parent_wnd_class && pw->window_number == dw->parent_wnd_num) { int parent_button = dw->parent_button; delete dw; return parent_button; } } return -1; }
benjeffery/openttd
src/widgets/dropdown.cpp
C++
gpl-2.0
15,681
/* * Movable Type (r) Open Source (C) 2001-2012 Six Apart, Ltd. * This program is distributed under the terms of the * GNU General Public License, version 2. * * $Id$ */ ;(function($) { var ES = MT.App.EditorStrategy; ES.Multi = function() { ES.apply(this, arguments) }; $.extend(ES.Multi.prototype, ES.prototype, { create: function(app, ids, format) { app.editors = {}; $.each(ids, function() { $('#' + this).show(); app.editors[this] = new MT.EditorManager(this, { format: format, wrap: true }); var setFormat = app.editors[this]['setFormat']; app.editors[this]['setFormat'] = function(format) { $.each(app.editors, function() { setFormat.apply(this, [format]); }); }; }); }, set: function(app, id) { var strategy = this; if (app.editor) { var height = app.editor.getHeight(); strategy._setWithHeight(app, id, height); } else { strategy._setWithHeight(app, id, null); } }, _setWithHeight: function(app, id, height) { $(app.editorIds).each(function() { if (id == this) { app.editors[this].show(); app.editor = app.editors[this]; if (height) { app.editor.setHeight(height); } } else { app.editors[this].hide(); } }); }, save: function() { app.editor.save(); } }); })(jQuery);
rosiro/MovableTypeOpenSource-5.2.2-yamucha
mt-static/js/editor/app/editor_strategy/multi.js
JavaScript
gpl-2.0
1,649
<?php //Create an Array for storing the dates that have events $dates_with_events = array(); //Grab posts (endpoints) $lcccevents = ''; $stockerevents = ''; $athleticevents = ''; $sportevents = ''; $categoryevents = ''; $domain = 'http://www.lorainccc.edu'; //$domain = 'http://' . $_SERVER['SERVER_NAME']; $lcccevents = new Endpoint( $domain . '/mylccc/wp-json/wp/v2/lccc_events/?per_page=100' ); $athleticevents = new Endpoint( $domain . '/athletics/wp-json/wp/v2/lccc_events/?per_page=100' ); $stockerevents = new Endpoint( 'http://sites.lorainccc.edu/stocker/wp-json/wp/v2/lccc_events/?per_page=100' ); //Create instance $multi = new MultiBlog( 1 ); $multi->add_endpoint ( $lcccevents ); $multi->add_endpoint ( $athleticevents ); $multi->add_endpoint ( $stockerevents ); //Fetch Posts(Events) from Endpoints $posts = $multi->get_posts(); if(empty($posts)){ echo 'No Posts Found!'; } //establishing current date for testing $currentdate = date("Y-m-d"); //Filling array with dates with events foreach ( $posts as $post ){ if( $post->event_end_date > $currentdate ){ array_push($dates_with_events, $post->event_end_date); } } $dates_with_events = array_unique($dates_with_events); $dates_with_events = array_filter($dates_with_events); $dates_with_events = array_values($dates_with_events); //echo '<br />'; //echo '<br />'; //echo 'Count: '.count($dates_with_events).'<br />'; //echo 'Without Empty: '.count($dates_with_events).'<br />'; //echo 'Events:'.'<br />'; /* for($y=0;$y < count($dates_with_events); $y++){ echo $y.': '.$dates_with_events[$y].'<br />'; } */ $current_month = date("n"); $current_year = date("Y"); $current_date = date("Y") . '-' . date("m") . '-' . date("d"); if(isset($_GET['disp_m'])){ $display_month = $_GET['disp_m']; $display_year = $_GET['disp_y']; } else { $display_month = $current_month; $display_year = $current_year; } $next_month = $display_month; $next_year = $display_year; $prev_month = $display_month; $prev_year = $display_year; if ($display_month == '12'){ $next_month = 1; $next_year = date("Y")+1; $prev_month -=1; } elseif($display_month > '12'){ $next_month = 1; $next_year = date("Y")+1; $prev_month = 12; } elseif($display_month < '12'){ $next_month +=1; $prev_month -=1; if ($prev_month == 0){ $prev_month = 12; $prev_year -=1; } } //echo 'Current Month: ' . $current_month . ' - ' . $current_year . '<br /><br />'; //echo 'Display Month: ' . $display_month . ' - ' . $display_year . '<br /><br />'; //echo 'Next Month: ' . $next_month . ' - ' . $next_year . '<br/><br />'; //echo 'Prev Month: ' . $prev_month . ' - ' . $prev_year . '<br/><br />'; $calendar = '<div id="calendar">'; $headings = array('Sun','Mon','Tues','Wed','Thurs','Fri','Sat'); $calendar .= '<div class="week heading"><div class="day heading"><div class="heading-text">'.implode('</div></div><div class="day heading"><div class="heading-text">', $headings).'</div></div></div>'; $running_day = date('w',mktime(0,0,0,$display_month,1,$display_year)); $days_in_month = date('t',mktime(0,0,0,$display_month,1,$display_year)); $days_in_this_week = 1; $day_counter = 0; $dates_array = array(); $calendar.= '<div class="week">'; for($x = 0; $x < $running_day; $x++): $calendar.= '<div class="day-np">&nbsp;</div>'; $days_in_this_week++; endfor; for($list_day = 1; $list_day <= $days_in_month; $list_day++): // determine if day is single digit or two, and transform to two digits if (strlen($list_day) == 1){ $day_of_week = '0' . $list_day; }else{ $day_of_week = $list_day; } // determine if month is single digit or two, and transform to two digits if (strlen($display_month) == 1){ $full_month = '0' . $display_month; }else{ $full_month = $display_month; } // fully formed date to match WordPress date variable $full_date = $display_year . '-' . $full_month . '-' . $day_of_week; if($full_date == $current_date){ $bol_valid = false; for($y=0;$y < count($dates_with_events); $y++){ if( $full_date == $dates_with_events[$y]){ $bol_valid = true; } } if($bol_valid == true){ $calendar.= '<a href="/mylccc/day?d='.$full_date.'">'; $calendar.= '<div class="day current-day">'; $calendar.= '<div class="day-number">'.$list_day.'</div>'; $calendar.= '<a class="calendar-event-listing" href="/mylccc/day?d='.$full_date.'"></a>'; $calendar.= '</div></a>'; } else{ $calendar.= '<div class="day current-day">'; $calendar.= '<div class="day-number">'.$list_day.'</div>'; $calendar.= '</div>'; } }else{ $bol_valid = false; for($y=0;$y < count($dates_with_events); $y++){ if( $full_date == $dates_with_events[$y]){ $bol_valid = true; } } if($bol_valid == true){ $calendar.= '<a style="display:block;" href="/mylccc/day?d='.$full_date.'">'; $calendar.= '<div class="day">'; $calendar.= '<div class="day-number">'.$list_day.'</div>'; $calendar.= '<a class="calendar-event-listing" href="/mylccc/day?d='.$full_date.'"></a>'; $calendar.= '</div></a>'; } else{ $calendar.= '<div class="day">'; $calendar.= '<div class="day-number">'.$list_day.'</div>'; $calendar.= '</div>'; } } if($running_day == 6): $calendar.= '</div>'; if(($day_counter+1) != $days_in_month): $calendar.= '<div class="week">'; endif; $running_day = -1; $days_in_this_week = 0; endif; $days_in_this_week++; $running_day++; $day_counter++; endfor; if($days_in_this_week < 8): for($x = 1; $x <= (8 - $days_in_this_week); $x++): $calendar.= '<div class="day-np">&nbsp;</div>'; endfor; endif; $plugin_image_dir = plugin_dir_url( 'lccc-news.php').'lccc-news/images/'; if ($prev_month < $current_month && $prev_year == $current_year){ echo '<div class="calendar-header">'; echo '<div class="header-placeholder">&nbsp;</div>'; echo '<div class="cur-month">' . date('F', mktime(0, 0, 0, $display_month, 10)) . ' ' . $display_year . '</div>'; echo '<div class="calendar-nav-next"><a href="?disp_m=' . $next_month . '&disp_y=' . $next_year . '"><img style="max-width:40%;" src="'.$plugin_image_dir.'Next-arrow.svg"></a></div></div><div style="clear:both;">'; echo '</div>'; }elseif($prev_month == $current_month && $prev_year == $current_year){ echo '<div class="calendar-header">'; echo '<div class="calendar-nav-prev"><a href="?disp_m=' . $prev_month . '&disp_y=' . $prev_year . '"><img style="max-width:40%;" src="'.$plugin_image_dir.'Prev-arrow.svg"></a></div>'; echo '<div class="cur-month">' . date('F', mktime(0, 0, 0, $display_month, 10)) . ' ' . $display_year . '</div>'; echo '<div class="calendar-nav-next"><a href="?disp_m=' . $next_month . '&disp_y=' . $next_year . '"><img style="max-width:40%;" src="'.$plugin_image_dir.'Next-arrow.svg"></a></div>'; echo '</div>'; echo '<div style="clear:both;"></div>'; }else{ echo '<div class="calendar-header">'; echo '<div class="calendar-nav-prev"><a href="?disp_m=' . $prev_month . '&disp_y=' . $prev_year . '"><img style="max-width:40%;" src="'.$plugin_image_dir.'Prev-arrow.svg"></a></div>'; echo '<div class="cur-month">' . date('F', mktime(0, 0, 0, $display_month, 10)) . ' ' . $display_year . '</div>'; echo '<div class="calendar-nav-next"><a href="?disp_m=' . $next_month . '&disp_y=' . $next_year . '"><img style="max-width:40%;" src="'.$plugin_image_dir.'Next-arrow.svg"></a></div>'; echo '</div>'; echo '<div style="clear:both;"></div>'; } echo $calendar; ?>
lorainccc/lccc-news
php/original-calendar-working.php
PHP
gpl-2.0
7,672
 namespace L2dotNET.GameService.model.skills2.speceffects { public class b_regen_mp_by_sit : TSpecEffect { public b_regen_mp_by_sit(double value) { this.value = value; } public override void OnStand(L2Player player) { if (mul) player.CharacterStat.URegMpMul -= value; else player.CharacterStat.SpecBonusRegMP -= value; } public override void OnSit(L2Player player) { if (mul) player.CharacterStat.URegMpMul += value; else player.CharacterStat.SpecBonusRegMP += value; } } }
domis045/L2dotNET
src/L2dotNET.Game/model/skills2/speceffects/b_regen_mp_by_sit.cs
C#
gpl-2.0
687
<?php /** * FW Gallery 3.0 * @copyright (C) 2014 Fastw3b * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * @link http://www.fastw3b.net/ Official website **/ defined( '_JEXEC' ) or die( 'Restricted access' ); JHTML :: _('behavior.framework', true); JHTML :: _('behavior.formvalidation'); JHTML :: script('administrator/components/com_fwgallery/assets/js/moorainbow.1.2b2.js'); JToolBarHelper :: title(JText::_('FWG_CONFIG').': <small><small>[ '.JText::_('FWG_EDIT').' ]</small></small>', 'fwgallery-config.png' ); JToolBarHelper::save(); JToolBarHelper::cancel(); $color = $this->obj->params->get('gallery_color'); if (preg_match('/[0-9a-fA-F]{3,6}/', $color)) $color = '#'.$color; else $color = ''; ?> <form action="index.php?option=com_fwgallery&amp;view=config" method="post" name="adminForm" id="adminForm" class="form-validate" enctype="multipart/form-data"> <div class="span6"> <fieldset class="adminform"> <legend><?php echo JText::_('FWG_IMAGE_SETTINGS'); ?></legend> <table class="admintable"> <tr> <td class="key"> <?php echo JText::_('FWG_THUMB_WIDTH'); ?> <span class="badge" title="<?php echo JText::_('FWG_TYPE_THE_WIDTH_FOR_THE_THUMBNAILS__THAT_WILL_SUIT_YOUR_NEEDS_MOST'); ?>">?</span><span class="badge badge-warning">*</span> </td> <td> <input type="text" class="inputbox required validate-numeric" name="config[im_th_w]" value="<?php echo $this->obj->params->get('im_th_w', 160); ?>" size="5"/> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_THUMB_HEIGHT'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_TYPE_THE_HEIGHT_FOR_THE_THUMBNAILS__THAT_WILL_SUIT_YOUR_NEEDS_MOST'); ?>">?</span>&nbsp;<span class="badge badge-warning">*</span> </td> <td> <input type="text" class="inputbox required validate-numeric" name="config[im_th_h]" value="<?php echo $this->obj->params->get('im_th_h', 120); ?>" size="5"/> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_MEDIUM_SIZE_WIDTH'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_THE_WIDTH_FOR_THE_MEDIUM_SIZE_IMAGE_DURING_FULL_SCREEN_VIEW'); ?>">?</span>&nbsp;<span class="badge badge-warning">*</span> </td> <td> <input type="text" class="inputbox required validate-numeric" name="config[im_mid_w]" value="<?php echo $this->obj->params->get('im_mid_w', 340); ?>" size="5"/> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_MEDIUM_SIZE_HEIGHT'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_THE_HEIGHT_FOR_THE_MEDIUM_SIZE_IMAGE_DURING_FULL_SCREEN_VIEW'); ?>">?</span>&nbsp;<span class="badge badge-warning">*</span> </td> <td> <input type="text" class="inputbox required validate-numeric" name="config[im_mid_h]" value="<?php echo $this->obj->params->get('im_mid_h', 255); ?>" size="5"/> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_BIG_SIZE_WIDTH'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_THE_PARAMETERS_OF_THE_IMAGE_FOR_LIGHTBOX_EFFECT_VIEW'); ?>">?</span>&nbsp;<span class="badge badge-warning">*</span> </td> <td> <input type="text" class="inputbox required validate-numeric" name="config[im_max_w]" value="<?php echo $this->obj->params->get('im_max_w', 800); ?>" size="5"/> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_BIG_SIZE_HEIGHT'); ?>&nbsp;<span class="badge" title=" title="<?php echo JText::_('FWG_THE_PARAMETERS_OF_THE_IMAGE_FOR_LIGHTBOX_EFFECT_VIEW'); ?>"">?</span>&nbsp;<span class="badge badge-warning">*</span> </td> <td> <input type="text" class="inputbox required validate-numeric" name="config[im_max_h]" value="<?php echo $this->obj->params->get('im_max_h', 600); ?>" size="5"/> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_THUMB_AND_MEDIUM_IMAGES_SHRINKING_METHOD'); ?> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'im_just_shrink', '', $this->obj->params->get('im_just_shrink'), JText :: _('FWG_JUST_SHRINK'), JText :: _('FWG_SHRINK_AND_CUT')); ?> </fieldset> </td> </tr> </table> </fieldset> <fieldset class="adminform"> <legend><?php echo JText::_('FWG_LAYOUT_SETTINGS'); ?></legend> <table class="admintable"> <tr> <td class="key"> <?php echo JText::_('FWG_GALLERIES_DEFAULT_COLOR'); ?>&nbsp;<span class="badge" title="<?php echo JText :: _('FWG_SELECT_ANY_COLOR_FROM_THE_COLOR_PALETTE_OR_JUST_TYPE_THE_COLOR__S_CODE__IF_YOU_KNOW_IT'); ?>">?</span> </td> <td id="color-row"<?php if ($color) { ?> style="background-color:<?php echo $color; ?>"<?php } ?>> <img id="myRainbow" src="<?php echo JURI :: root(true); ?>/administrator/components/com_fwgallery/assets/images/rainbow.png" alt="[r]" width="16" height="16" /> <input id="color" name="config[gallery_color]" type="text" size="13" value="<?php echo $color; ?>" /> <button type="button" id="myRainbowButton"><?php echo JText :: _('FWG_SELECT'); ?></button> <button type="button" id="myRainbowClearButton"><?php echo JText :: _('FWG_CLEAR'); ?></button> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_GALLERIES_IN_A_ROW'); ?> &nbsp;<span class="badge" title="<?php echo JText :: _('FWG_THE_NUMBER_DEPENDS_ON_THE_THUMB_SIZES_AND_THE_TEMPLATE_OF_YOUR_SITE__OBLIGATORY_FIELD'); ?>">?</span><span class="badge badge-warning">*</span> </td> <td> <?php echo JHTML :: _('select.genericlist', $this->columns, 'config[galleries_a_row]', '', 'id', 'name', $this->obj->params->get('galleries_a_row', 3)); ?> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_IMAGES_IN_A_ROW'); ?> &nbsp;<span class="badge" title="<?php echo JText :: _('FWG_THE_NUMBER_DEPENDS_ON_THE_THUMB_SIZES_AND_THE_TEMPLATE_OF_YOUR_SITE__OBLIGATORY_FIELD'); ?>">?</span><span class="badge badge-warning">*</span> </td> <td> <?php echo JHTML :: _('select.genericlist', $this->columns, 'config[images_a_row]', '', 'id', 'name', $this->obj->params->get('images_a_row', 3)); ?> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_GALLERIES_ROWS_PER_PAGE'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_TYPE_THE_NUMBER_OF_GALLERIES__YOU_WANT_TO_BE_DISPLAYED_PER_PAGE'); ?>">?</span> </td> <td> <input type="text" class="inputbox required validate-numeric" name="config[galleries_rows]" value="<?php echo $this->obj->params->get('galleries_rows', 4); ?>" size="5"/> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_IMAGES_ROWS_PER_PAGE'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_TYPE_THE_NUMBER_OF_IMAGES_YOU_WANT_TO_BE_DISPLAYED_PER_PAGE'); ?>">?</span> </td> <td> <input type="text" class="inputbox required validate-numeric" name="config[images_rows]" value="<?php echo $this->obj->params->get('images_rows', 4); ?>" size="5"/> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DEFAULT_GALLERIES_ORDERING'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_SELECT_ONE_OF_THE_FOUR_GALLERIES___ORDER_TYPES__THIS_OPTION_IS_AVAILABLE_ON_FRONT_END_TOO'); ?>">?</span> </td> <td> <?php echo JHTML :: _('select.genericlist', array( JHTML :: _('select.option', 'name', JText :: _('FWG_ALPHABETICALLY'), 'id', 'name'), JHTML :: _('select.option', 'new', JText :: _('FWG_NEWEST_FIRST'), 'id', 'name'), JHTML :: _('select.option', 'old', JText :: _('FWG_OLDEST_FIRST'), 'id', 'name'), JHTML :: _('select.option', 'order', JText :: _('FWG_ORDERING'), 'id', 'name') ), 'config[ordering_galleries]', '', 'id', 'name', $this->obj->params->get('ordering_galleries', 'order')); ?> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DEFAULT_IMAGES_ORDERING'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_SELECT_ONE_OF_THE_FOUR_POSSIBLE_TYPES_OF_ORDER_FOR_IMAGES__THE_OPTION_IS_AVAILABLE_ON_FRONT_END_TOO'); ?>">?</span> </td> <td> <?php echo JHTML :: _('select.genericlist', array( JHTML :: _('select.option', 'name', JText :: _('FWG_ALPHABETICALLY'), 'id', 'name'), JHTML :: _('select.option', 'new', JText :: _('FWG_NEWEST_FIRST'), 'id', 'name'), JHTML :: _('select.option', 'old', JText :: _('FWG_OLDEST_FIRST'), 'id', 'name'), JHTML :: _('select.option', 'order', JText :: _('FWG_ORDERING'), 'id', 'name'), JHTML :: _('select.option', 'voting', JText :: _('FWG_VOTING'), 'id', 'name') ), 'config[ordering_images]', '', 'id', 'name', $this->obj->params->get('ordering_images', 'order')); ?> </td> </tr> </table> </fieldset> <fieldset class="adminform"> <legend><?php echo JText::_('FWG_WATERMARK'); ?></legend> <table class="admintable"> <tr> <td class="key"> <?php echo JText::_('FWG_USE_WATERMARK'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_YES_NO_OPTION__IF_YOU_DON__T_WANT_TO_USE_IT__THEN_SELECT__QUOT_NO_QUOT__HERE'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'use_watermark', '', $this->obj->params->get('use_watermark')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_WATERMARK_POSITION'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_SELECT_ONE_OF_THE_5_POSSIBLE_LOCATIONS_OF_THE_WATERMARK_SIGN_ON_IMAGES'); ?>">?</span> </td> <td> <?php echo JHTML :: _('select.genericlist', array( JHTML :: _('select.option', 'center', JText :: _('FWG_CENTER'), 'id', 'name'), JHTML :: _('select.option', 'left top', JText :: _('FWG_LEFT_TOP'), 'id', 'name'), JHTML :: _('select.option', 'right top', JText :: _('FWG_RIGHT_TOP'), 'id', 'name'), JHTML :: _('select.option', 'left bottom', JText :: _('FWG_LEFT_BOTTOM'), 'id', 'name'), JHTML :: _('select.option', 'right bottom', JText :: _('FWG_RIGHT_BOTTOM'), 'id', 'name') ), 'config[watermark_position]', '', 'id', 'name', $this->obj->params->get('watermark_position', 'left bottom')); ?> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_WATERMARK_FILE'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_UPLOAD_A_FILE__THAT_WILL_BE_USED_AS_A_WATERMARK_ON_IMAGES'); ?>">?</span> </td> <td> <?php if ($this->obj->params->get('watermark_file')) { if ($path = JFHelper :: getWatermarkFilename()) { ?> <img src="<?php echo JURI :: root(true); ?>/<?php echo $path; ?>" /><br/> <input type="checkbox" name="delete_watermark" value="1" /> <?php echo JText :: _('FWG_REMOVE_WATERMARK'); ?><br/> <?php } else { ?> <p style="color:#f00;"><?php echo JText :: _('FWG_WATERMARK_FILE_NOT_FOUND_'); ?></p> <?php } } ?> <input id="watermark_file" type="file" class="inputbox" name="watermark_file" /> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_WATERMARK_TEXT'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_TYPE_A_TEXT__THAT_WILL_BE_USED_AS_A_WATERMARK__IF_YOU_UPLOAD_A_FILE__THEN_TEXT_WON__T_BE_DISPLAYED'); ?>">?</span> </td> <td> <input type="text" class="inputbox" name="config[watermark_text]" value="<?php echo $this->obj->params->get('watermark_text'); ?>" size="35"/> </td> </tr> </table> </fieldset> <fieldset class="adminform"> <legend><?php echo JText::_('FWG_VOTING_SYSTEM'); ?></legend> <table class="admintable"> <tr> <td class="key"> <?php echo JText::_('FWG_USE_VOTING'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_YES_NO_OPTION__SELECT__QUOT_NO_QUOT__IF_YOU_DON__T_WANT_TO_USE_VOTING_AT_ALL'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'use_voting', '', $this->obj->params->get('use_voting')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_PUBLIC_VOTING'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_LET_THE_VISITORS_PUBLIC_POLLS'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'public_voting', '', $this->obj->params->get('public_voting')); ?> </fieldset> </td> </tr> </table> </fieldset> </div> <div class="span6"> <fieldset class="adminform"> <legend><?php echo JText::_('FWG_DISPLAYING_SETTINGS'); ?></legend> <table class="admintable"> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_TOTAL_GALLERIES_COUNTER'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_YES_NO_OPTION__SELECT__QUOT_NO_QUOT___IF_YOU_WANT_TO_HIDE_IT'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_total_galleries', '', $this->obj->params->get('display_total_galleries')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_GALLERY_OWNER_NAME'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_YES_NO_OPTION__SELECT__QUOT_NO_QUOT___IF_YOU_WANT_TO_HIDE_IT'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_owner_gallery', '', $this->obj->params->get('display_owner_gallery')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_IMAGE_OWNER_NAME'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_YES_NO_OPTION__SELECT__QUOT_NO_QUOT___IF_YOU_WANT_TO_HIDE_IT'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_owner_image', '', $this->obj->params->get('display_owner_image')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_GALLERY_DATE'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_SHOW_OR_HIDE_THE_CREATION_DATE_OF_THE_GALLERY__BY_SELECTING_YES_NO'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_date_gallery', '', $this->obj->params->get('display_date_gallery')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_ORDER_BY_OPTION'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_YES_NO_OPTION__SELECT__QUOT_NO_QUOT___IF_YOU_WANT_TO_HIDE_IT_IN_THE_FRONT_END'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_gallery_sorting', '', $this->obj->params->get('display_gallery_sorting')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_GALLERY_NAME'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_SHOW_OR_HIDE_THE_NAME_OF_THE_GALLERY__CLICKING_YES_NO'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_name_gallery', '', $this->obj->params->get('display_name_gallery')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_IMAGE_NAME'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_SHOW_OR_HIDE_THE_NAME_OF_THE_IMAGES___ADDING_TO_THE_GALLERY__CLICKING_YES_NO'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_name_image', '', $this->obj->params->get('display_name_image')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_IMAGE_DATE'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_SHOW_OR_HIDE_THE_DATE_OF_THE_IMAGES___ADDING_TO_THE_GALLERY__CLICKING_YES_NO'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_date_image', '', $this->obj->params->get('display_date_image')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_IMAGE_VIEWS'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_SHOW_OR_HIDE_THE_NUMBER_OF_IMAGE_VIEWS__SELECTING_YES_NO_OPTIONS'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_image_views', '', $this->obj->params->get('display_image_views')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_ALLOW_IMAGE_DOWNLOAD'); ?> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'allow_image_download', '', $this->obj->params->get('allow_image_download')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_IMAGE_TAGS'); ?> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_image_tags', '', $this->obj->params->get('display_image_tags')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_ALLOW_PRINT_BUTTON'); ?> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'allow_print_button', '', $this->obj->params->get('allow_print_button')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_HIDE_BOTTOM_IMAGES'); ?> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'hide_bottom_image', '', $this->obj->params->get('hide_bottom_image')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_USERS_COPYRIGHT'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_SHOW_OR_HIDE_USERS_COPYRIGHT_SELECTING_YES_NO'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_user_copyright', '', $this->obj->params->get('display_user_copyright')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DATE_FORMAT'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_SET_A_SUITABLE_DATE_FORMAT_FOR_THE_FRONT_END__MONTH__DAY_AND_YEAR'); ?>">?</span> </td> <td> <input type="text" class="inputbox" name="config[date_format]" value="<?php echo $this->obj->params->get('date_format', '%B %d, %Y'); ?>" size="15"/> &nbsp;<a href="http://docs.joomla.org/How_do_you_change_the_date_format%3F" target="_blank"><?php echo JText::_('FWG_DATE_OPTIONS'); ?></a> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_ICON_NEW_DAYS'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_THE_NUMBER_OF_DAYS__WHEN_ADDED_IMAGE_WILL_HAVE_THE_ICON__QUOT_NEW_QUOT__IN_THE_LEFT_TOP'); ?>">?</span> </td> <td> <input type="text" class="inputbox" name="config[new_days]" value="<?php echo $this->obj->params->get('new_days', 7); ?>" size="5"/> </td> </tr> <tr> <td class="key"> <?php echo JText :: _('FWG_DISPLAY_LIGHTBOX_GALLERIES'); ?> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_galleries_lightbox', '', $this->obj->params->get('display_galleries_lightbox')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_HIDE_MIGNIFIER__LIGHTBOX_EFFECT_'); ?> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'hide_mignifier', '', $this->obj->params->get('hide_mignifier')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_HIDE_SINGLE_IMAGE_VIEW'); ?> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'hide_single_image_view', '', $this->obj->params->get('hide_single_image_view')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_HIDE_IPHONE_APP_PROMO'); ?> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'hide_iphone_app_promo', '', $this->obj->params->get('hide_iphone_app_promo')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_SOCIAL_SHARING'); ?> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_social_sharing', '', $this->obj->params->get('display_social_sharing')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_HIDE_FASTW3B_COPYRIGHT'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_IF_YOU_DON__T_WANT_TO_DISPLAY_FASTW3B_COPYRIGHT_ON_THE_FRONT_END_OF_YOUR_WEBSITE__THEN_SELECT__QUOT_NO_QUOT__HERE'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'hide_fw_copyright', '', $this->obj->params->get('hide_fw_copyright')); ?> </fieldset> <div id="fw-copyright-donation" style="display:none"> <?php echo JText :: _('FWG_FWGALLERY_COPYRIGHT_HIDE'); ?> </div> </td> </tr> </table> </fieldset> <?php if ($this->plugins) { ?> <fieldset class="adminform"> <legend><?php echo JText::_('FWG_ADDITIONAL_SETTINGS'); ?></legend> <?php foreach ($this->plugins as $plugin) if ($plugin) { ?> <fieldset class="adminform"> <?php echo $plugin; ?> </fieldset> <?php } ?> </fieldset> <?php } ?> </div> <div style="clear:both;"></div> <input type="hidden" name="task" value="" /> </form> <script type="text/javascript"> var copyrightEff; var fwgRainbow; window.addEvent('domready', function() { document.getElement('#myRainbowButton').addEvent('click', function(ev) { document.getElement('#myRainbow').fireEvent('click', ev); }); document.getElement('#myRainbowClearButton').addEvent('click', function(ev) { document.getElement('#color').value = ''; document.getElement('#color-row').setStyle('background-color', ''); }); document.getElement('#color').addEvent('keyup', function() { if (this.value.match(/^#[0-9a-fA-F]{3,6}$/)) { document.getElement('#color-row').setStyle('background-color', this.value); fwgRainbow.manualSet(this.value, 'hex'); } else { document.getElement('#color-row').setStyle('background-color', ''); } }); fwgRainbow = new MooRainbow('myRainbow', { wheel: true, imgPath: '<?php echo JURI :: root(true); ?>/administrator/components/com_fwgallery/assets/images/', onChange: function(color) { document.getElement('#color').value = color.hex; document.getElement('#color-row').setStyle('background-color', color.hex); }, onComplete: function(color) { document.getElement('#color').value = color.hex; document.getElement('#color-row').setStyle('background-color', color.hex); } }); <?php if ($color) { ?> fwgRainbow.manualSet('<?php echo $color; ?>', 'hex'); <?php } ?> document.getElements('#adminForm input').each(function (el) { if (el.name == 'hide_fw_copyright') { el.addEvent('click', check_copyright); el.addEvent('change', check_copyright); } }); copyrightEff = new Fx.Slide(document.getElement('#fw-copyright-donation')); copyrightEff.hide(); document.getElement('#fw-copyright-donation').setStyle('display', ''); check_copyright(); }); function check_copyright() { document.getElements('#adminForm input').each(function (el) { if (el.name == 'hide_fw_copyright' && el.checked) { if (el.value == '0') copyrightEff.slideOut(); else copyrightEff.slideIn() } }); } Joomla.submitbutton = function(task) { if (task == 'save') { if (!document.formvalidator.isValid(document.getElement('#adminForm'))) { alert('<?php echo JText :: _('FWG_NOT_ALL_REQUIRED_FIELDS_PROPERLY_FILLED_IN'); ?>'); return; } if (document.getElement('#watermark_file') && document.getElement('#watermark_file').value && !document.getElement('#watermark_file').value.match(/\.png$/i)) { alert('<?php echo JText :: _('FWG_ALLOWED_PNG_AND_GIF_FILES_AS_WATERMARK_IMAGES_ONLY'); ?>'); return; } } document.getElement('#adminForm').task.value = task; document.getElement('#adminForm').submit(); } </script>
Jbouska419/craftsman
administrator/components/com_fwgallery/views/config/tmpl/edit.php
PHP
gpl-2.0
27,789
<?php /* * @version $Id: ruleticket.php 22657 2014-02-12 16:17:54Z moyo $ ------------------------------------------------------------------------- GLPI - Gestionnaire Libre de Parc Informatique Copyright (C) 2003-2014 by the INDEPNET Development Team. http://indepnet.net/ http://glpi-project.org ------------------------------------------------------------------------- LICENSE This file is part of GLPI. GLPI is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GLPI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GLPI. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ /** @file * @brief */ include ('../inc/includes.php'); $rulecollection = new RuleTicketCollection($_SESSION['glpiactive_entity']); include (GLPI_ROOT . "/front/rule.common.php"); ?>
elitelinux/hack-space
php/front/ruleticket.php
PHP
gpl-2.0
1,285
<?php /** * Action functions * * Inject content through template hooks * */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly if ( ! function_exists( 'wolf_404_bg' ) ) { /** * Output 404 page background CSS in head * * @access public * @since 1.0.0 * @return void */ function wolf_404_bg() { if ( is_404() && wolf_get_theme_option( '404_bg' ) ) { ?> <style type="text/css"> .error404 #page-content{ background-image: url(<?php echo esc_url( wolf_get_url_from_attachment_id( wolf_get_theme_option( '404_bg' ), 'extra-large' ) ); ?>); } </style> <?php } } add_action( 'wp_head', 'wolf_404_bg' ); } if ( ! function_exists( 'wolf_scroll_arrow' ) ) { /** * Output scroll arrow * * @access public * @since 1.0.0 * @return void */ function wolf_scroll_arrow() { if ( ! is_404() ) ?> <div id="top"></div><a id="top-arrow" class="scroll" href="#top"></a> <?php } add_action( 'wolf_body_start', 'wolf_scroll_arrow' ); } if ( ! function_exists( 'wolf_page_loader' ) ) { /** * Output loader overlay * * @access public * @since 1.0.0 * @return void */ function wolf_page_loader() { if ( wolf_get_theme_option( 'page_transition' ) ) : $loader = wolf_get_theme_option( 'loader_type' ); ?> <div id="loading-overlay"><div id="loader"> <?php if ( wolf_get_theme_option( 'loading_logo' ) ) : ?> <img id="loading-logo" src="<?php echo esc_url( wolf_get_url_from_attachment_id( wolf_get_theme_option( 'loading_logo' ), 'logo' ) ); ?>" alt="loading-logo"> <?php endif; ?> <?php if ( wolf_get_theme_option( 'loader' ) ) : ?> <?php if ( 'loader1' == $loader ) : ?> <div class="loader1"></div> <?php elseif ( 'loader2' == $loader ) : ?> <div class="loader2"> <div class="loader2-double-bounce1"></div> <div class="loader2-double-bounce2"></div> </div> <?php elseif ( 'loader3' == $loader ) : ?> <div class="loader3"> <div class="loader3-rect1"></div> <div class="loader3-rect2"></div> <div class="loader3-rect3"></div> <div class="loader3-rect4"></div> <div class="loader3-rect5"></div> </div> <?php elseif ( 'loader4' == $loader ) : ?> <div class="loader4"> <div class="loader4-cube1"></div> <div class="loader4-cube2"></div> </div> <?php elseif ( 'loader5' == $loader ) : ?> <!-- <div class="loader5"></div> --> <div class="loading"> <div class="loading-bar"></div> <div class="loading-bar"></div> <div class="loading-bar"></div> <div class="loading-bar"></div> </div> <?php elseif ( 'loader6' == $loader ) : ?> <div class="loader6"> <div class="loader6-dot1"></div> <div class="loader6-dot2"></div> </div> <?php elseif ( 'loader7' == $loader ) : ?> <div class="loader7"> <div class="loader7-bounce1"></div> <div class="loader7-bounce2"></div> <div class="loader7-bounce3"></div> </div> <?php elseif ( 'loader8' == $loader ) : ?> <div class="loader8"> <div class="loader8-container loader8-container1"> <div class="loader8-circle1"></div> <div class="loader8-circle2"></div> <div class="loader8-circle3"></div> <div class="loader8-circle4"></div> </div> <div class="loader8-container loader8-container2"> <div class="loader8-circle1"></div> <div class="loader8-circle2"></div> <div class="loader8-circle3"></div> <div class="loader8-circle4"></div> </div> <div class="loader8-container loader8-container3"> <div class="loader8-circle1"></div> <div class="loader8-circle2"></div> <div class="loader8-circle3"></div> <div class="loader8-circle4"></div> </div> </div> <?php endif; ?> <?php endif; ?> </div></div> <?php endif; } add_action( 'wolf_body_start', 'wolf_page_loader' ); } if ( ! function_exists( 'wolf_top_search_form' ) ) { /** * Output search form * * @access public * @since 1.0.0 * @return void */ function wolf_top_search_form() { if ( wolf_get_theme_option( 'search_menu_item' ) ) { echo '<div id="top-search-form-container"><div id="top-search-form">'; get_search_form(); echo '</div></div>'; } } add_action( 'wolf_body_start', 'wolf_top_search_form' ); } if ( ! function_exists( 'wolf_output_message_bar' ) ) { /** * Output message bar plugin function * * @access public * @since 1.0.0 * @return void */ function wolf_output_message_bar() { if ( function_exists( 'wolf_message_bar' ) ) wolf_message_bar(); } add_action( 'wolf_body_start', 'wolf_output_message_bar' ); } if ( ! function_exists( 'wolf_output_top_bar' ) ) { /** * Output message bar plugin function * * @access public * @since 1.0.0 * @return void */ function wolf_output_top_bar() { if ( wolf_get_theme_option( 'top_bar' ) && 'left' != wolf_get_theme_option( 'menu_position' ) ) { get_template_part( 'partials/top', 'bar' ); } } add_action( 'wolf_body_start', 'wolf_output_top_bar' ); } if ( ! function_exists( 'wolf_main_menu' ) ) { /** * Output main menu * * @access public * @since 1.0.0 * @return void */ function wolf_main_menu() { if ( 'default' == wolf_get_theme_option( 'menu_position' ) || 'center' == wolf_get_theme_option( 'menu_position' ) ) { echo '<div id="ceiling">'; get_template_part( 'partials/navigation/navigation', 'desktop' ); echo '</div>'; } } add_action( 'wolf_body_start', 'wolf_main_menu' ); } if ( ! function_exists( 'wolf_main_menu_logo_centered' ) ) { /** * Output main menu * * @access public * @since 1.0.0 * @return void */ function wolf_main_menu_logo_centered() { if ( 'logo-centered' == wolf_get_theme_option( 'menu_position' ) ) { echo '<div id="ceiling">'; get_template_part( 'partials/navigation/navigation', 'logo-centered' ); echo '</div>'; } } add_action( 'wolf_body_start', 'wolf_main_menu_logo_centered' ); } if ( ! function_exists( 'wolf_left_main_menu' ) ) { /** * Output main menu * * @access public * @since 1.0.0 * @return void */ function wolf_left_main_menu() { if ( 'left' == wolf_get_theme_option( 'menu_position' ) ) get_template_part( 'partials/navigation/navigation', 'left' ); } add_action( 'wolf_site_content_start', 'wolf_left_main_menu' ); } if ( ! function_exists( 'wolf_output_mobile_hello_bar' ) ) { /** * Output mobile hello bar * * @access public * @since 1.0.0 * @return void */ function wolf_output_mobile_hello_bar() { if ( 'modern' != wolf_get_theme_option( 'menu_position' ) ) : ?> <div id="mobile-bar" class="clearfix"> <div id="mobile-bar-inner"> <div id="menu-toggle" class="menu-toggle"> <div class="burger-before"></div> <div class="burger"></div> <div class="burger-after"></div> </div> <?php echo wolf_logo(); ?> </div> </div> <?php endif; } add_action( 'wolf_body_start', 'wolf_output_mobile_hello_bar' ); } if ( ! function_exists( 'wolf_output_side_menu_toggle' ) ) { /** * Output Secondary Menu toggle * * @access public * @since 1.0.0 * @return void */ function wolf_output_side_menu_toggle() { $menus = array( 'default', 'center', 'logo-centered' ); if ( wolf_get_theme_option( 'additional_toggle_menu' ) && in_array( wolf_get_theme_option( 'menu_position' ), $menus ) ) : ?> <div id="side-menu-toggle" class="toggle-add-menu"><div class="plus"></div></div> <?php endif; } add_action( 'wolf_body_start', 'wolf_output_side_menu_toggle' ); } if ( ! function_exists( 'wolf_additional_menu' ) ) { /** * Output secondary menu * * @access public * @since 1.0.0 * @return void */ function wolf_additional_menu() { if ( wolf_get_theme_option( 'additional_toggle_menu' ) && ( 'default' == wolf_get_theme_option( 'menu_position' ) || 'center' == wolf_get_theme_option( 'menu_position' ) || 'logo-centered' == wolf_get_theme_option( 'menu_position' ) ) ) { if ( 'side' == wolf_get_theme_option( 'additional_toggle_menu_type' ) ) get_template_part( 'partials/navigation/navigation', 'side-panel' ); if ( 'overlay' == wolf_get_theme_option( 'additional_toggle_menu_type' ) ) get_template_part( 'partials/navigation/navigation', 'overlay' ); } } add_action( 'wolf_body_start', 'wolf_additional_menu' ); } if ( ! function_exists( 'wolf_mobile_menu' ) ) { /** * Output mobile menu * * @access public * @since 1.0.0 * @return void */ function wolf_mobile_menu() { if ( 'modern' != wolf_get_theme_option( 'menu_position' ) ) get_template_part( 'partials/navigation/navigation', 'mobile' ); } add_action( 'wolf_body_start', 'wolf_mobile_menu' ); } if ( ! function_exists( 'wolf_modern_menu_toggle' ) ) { /** * Output modern menu * * @access public * @since 1.0.0 * @return void */ function wolf_modern_menu_toggle() { if ( 'modern' == wolf_get_theme_option( 'menu_position' ) ) { ?> <div id="menu-toggle-modern" class="menu-toggle"> <div class="burger-before"></div> <div class="burger"></div> <div class="burger-after"></div> </div> <?php } } add_action( 'wolf_body_start', 'wolf_modern_menu_toggle' ); } if ( ! function_exists( 'wolf_modern_menu_overlay' ) ) { /** * Output modern menu overlay * * @access public * @since 1.0.0 * @return void */ function wolf_modern_menu_overlay() { if ( 'modern' == wolf_get_theme_option( 'menu_position' ) ) { ?> <div id="modern-menu-overlay"></div> <?php } } add_action( 'wolf_body_start', 'wolf_modern_menu_overlay' ); } if ( ! function_exists( 'wolf_modern_menu' ) ) { /** * Output modern menu * * @access public * @since 1.0.0 * @return void */ function wolf_modern_menu() { if ( 'modern' == wolf_get_theme_option( 'menu_position' ) ) get_template_part( 'partials/navigation/navigation', 'modern' ); } add_action( 'wolf_body_start', 'wolf_modern_menu' ); } if ( ! function_exists( 'wolf_cart_menu_item' ) ) { /** * Add a cart menu item * * @access public * @since 1.0.0 * @param * @return void */ function wolf_cart_menu_item ( $items, $args ) { if ( class_exists( 'WooCommerce' ) && function_exists( 'wc_get_page_id' ) ) { $cart_url = get_permalink( wc_get_page_id( 'cart' ) ); $woo_item = '<li class="cart-menu-item">'; $woo_item .= "<a class='cart-menu-item-link' href='$cart_url'>"; $woo_item .= '<span class="product-count">' . WC()->cart->cart_contents_count . '</span>'; $woo_item .= '<span class="cart-text">' . __( 'Cart', 'wolf' ) . '</span>'; $woo_item .= '</a>'; $woo_item .= '<span class="cart-menu-panel">'; $woo_item .= "<a href='$cart_url'>"; $woo_item .= '<span class="icon-cart"></span>'; $woo_item .= '<span class="panel-product-count">'; $woo_item .= sprintf( _n( '%d item', '%d items', WC()->cart->cart_contents_count, 'wolf' ), WC()->cart->cart_contents_count ); $woo_item .= '</span></br>'; // count $woo_item .= '<span class="panel-total">'; $woo_item .= __( 'Total', 'wolf' ) . ' ' . WC()->cart->get_cart_total(); $woo_item .= '</span>'; // total //' . __( 'Total', 'wolf' ) . ' ' . $total . ' $woo_item .= '</a>'; $woo_item .= '</span>'; $woo_item .= '</li>'; // var_dump( $woocommerce->cart ); if ( ( $args->theme_location == 'primary' || $args->theme_location == 'primary-right' ) && wolf_get_theme_option( 'cart_menu_item' ) ) { $items .= $woo_item; } } return $items; } add_filter( 'wp_nav_menu_items', 'wolf_cart_menu_item', 10, 2 ); } if ( ! function_exists( 'wolf_main_menu_socials' ) ) { /** * Output social icons in main menu * * @access public * @since 1.0.0 * @return void */ function wolf_main_menu_socials( $items, $args ) { $services = wolf_get_theme_option( 'menu_socials_services' ); $socials_item = ''; if ( $services ) { $socials_item = '<li class="socials-menu-item">'; $socials_item .= wolf_theme_socials( $services, '1x', 'span' ); $socials_item .= '</li>'; } if ( 'default' == wolf_get_theme_option( 'menu_position' ) || 'logo-centered' == wolf_get_theme_option( 'menu_position' ) ) { if ( $args->theme_location == 'primary' || $args->theme_location == 'primary-right' ) { $items .= $socials_item; } } return $items; } add_filter( 'wp_nav_menu_items', 'wolf_main_menu_socials', 10, 2 ); } if ( ! function_exists( 'wolf_search_menu_item' ) ) { /** * Add a search menu item * * @access public * @since 1.0.0 * @return void */ function wolf_search_menu_item( $items, $args ) { $search_item = '<li class="search-menu-item"> <a class="search-menu-item-link" href="#"> <span class="search-text">' . __( 'Search', 'wolf' ) . '</span></a></li>'; if ( ( $args->theme_location == 'primary' || $args->theme_location == 'primary-right' ) && wolf_get_theme_option( 'search_menu_item' ) ) { $items .= $search_item; } return $items; } add_filter( 'wp_nav_menu_items', 'wolf_search_menu_item', 10, 2 ); } if ( ! function_exists( 'wolf_toggle_menu_item' ) ) { /** * Add a toggle menu item */ function wolf_toggle_menu_item ( $items, $args ) { $menus = array( 'default', 'center', 'logo-centered' ); $toggle_text = wolf_get_theme_option( 'toggle_side_menu_item_text' ); $toggle_item = '<li class="toggle-menu-item"><a class="toggle-menu-item-link toggle-add-menu" href="#">'; if ( $toggle_text ) $toggle_item .= '<span class="toggle-text">' . $toggle_text . '</span>'; $toggle_item .= '</a></li>'; if ( ( $args->theme_location == 'primary' || $args->theme_location == 'primary-right' ) && wolf_get_theme_option( 'additional_toggle_menu' ) && in_array( wolf_get_theme_option( 'menu_position' ), $menus ) ) { $items .= $toggle_item; } return $items; } add_filter( 'wp_nav_menu_items', 'wolf_toggle_menu_item', 10, 2 ); } if ( ! function_exists( 'wolf_header_overlay' ) ) { /** * Output home header */ function wolf_header_overlay() { if ( ! wolf_is_slider_in_home_header() && 'wolf_slider' != wolf_get_theme_option( 'home_header_type' ) ) : ?> <div class="header-overlay"></div> <?php endif; } add_action( 'wolf_header_start', 'wolf_header_overlay' ); } if ( ! function_exists( 'wolf_home_header' ) ) { /** * Output home header */ function wolf_home_header() { if ( is_front_page() && ! is_paged() || is_page_template( 'page-templates/home.php' ) && 'none' != wolf_get_theme_option( 'home_header_type' ) ) get_template_part( 'partials/header', 'home' ); } add_action( 'wolf_header_start', 'wolf_home_header' ); } if ( ! function_exists( 'wolf_header_gallery_slideshow' ) ) { /** * Output header gallery slideshow */ function wolf_header_gallery_slideshow() { if ( is_single() && 'gallery' == get_post_format() ) { get_template_part( 'partials/slider', 'header-gallery' ); } } add_action( 'wolf_header_start', 'wolf_header_gallery_slideshow' ); } if ( ! function_exists( 'wolf_scroll_down_arrow' ) ) { /** * Output scroll down arrow */ function wolf_scroll_down_arrow() { if ( wolf_get_theme_option( 'scroll_down_arrow' ) ) { ?> <a id="scroll-down" class="scroll" href="#main"></a> <?php } } add_action( 'wolf_header_end', 'wolf_scroll_down_arrow' ); } if ( ! function_exists( 'wolf_share_links' ) ) { /** * Share links below single posts * * @param bool $display * @return string */ function wolf_share_links() { $post_type = get_post_type(); if ( wolf_get_theme_option( $post_type . '_share' ) ) { // is theme option checked get_template_part( 'partials/share', 'post' ); } } add_action( 'wolf_post_end_singular', 'wolf_share_links' ); } if ( ! function_exists( 'wolf_author_meta' ) ) { /** * Output author bio box */ function wolf_author_meta() { if ( wolf_get_theme_option( 'show_author_box' ) && 'post' == get_post_type() || 'review' == get_post_type() ) { get_template_part( 'partials/author', 'bio' ); } } add_action( 'wolf_post_end_singular', 'wolf_author_meta' ); } if ( ! function_exists( 'wolf_display_author_info_in_author_archive' ) ) { /** * Display the author info at the top of the author archive pages */ function wolf_display_author_info_in_author_archive() { if ( is_author() && wolf_get_theme_option( 'show_author_box' ) ) get_template_part( 'partials/author', 'bio' ); } add_action( 'wolf_page_before', 'wolf_display_author_info_in_author_archive' ); } if ( ! function_exists( 'wolf_output_music_network' ) ) { /** * Output music network icons */ // function wolf_output_music_network() { // if ( function_exists( 'wolf_music_network' ) ) { // if ( wolf_is_music_network() ) { // echo '<div class="music-social-icons-container">'; // wolf_music_network(); // echo '</div>'; // } // } // } add_action( 'wolf_footer_before', 'wolf_output_music_network' ); } if ( ! function_exists( 'wolf_bottom_menu' ) ) { /** * Output bottom menu */ function wolf_bottom_menu() { if ( has_nav_menu( 'tertiary' ) ) { ?> <nav id="site-navigation-tertiary" class="wrap navigation tertiary-navigation" role="navigation"> <?php wp_nav_menu( array( 'theme_location' => 'tertiary', 'menu_class' => 'nav-menu-tertiary inline-list', 'fallback_cb' => '', 'depth' => 1, ) ); ?> </nav><!-- #site-navigation-tertiary--> <?php } } add_action( 'wolf_footer_end', 'wolf_bottom_menu' ); } if ( ! function_exists( 'wolf_bottom_socials' ) ) { /** * Output social icons * * @access public * @since 1.0.0 * @return void */ function wolf_bottom_socials() { if ( wolf_get_theme_option( 'bottom_socials' ) ) { $services = wolf_get_theme_option( 'bottom_socials_services' ); echo wolf_theme_socials( $services, '1x' ); } } add_action( 'wolf_footer_end', 'wolf_bottom_socials' ); } if ( ! function_exists( 'wolf_output_pagination' ) ) { /** * Output pagination on blog page * * @access public * @since 1.0.0 * @return void */ function wolf_output_pagination() { if ( wolf_is_blog() ) { get_template_part( 'partials/pagination' ); } } add_action( 'wolf_page_after', 'wolf_output_pagination' ); } if ( ! function_exists( 'wolf_print_post_navigation' ) ) { /** * Output related post or post nav depending on metabox * * @access public * @since 1.0.0 * @return void */ function wolf_print_post_navigation() { $nav_type = wolf_get_single_blog_post_nav_type(); $post_types = array( 'post' ); if ( in_array( get_post_type(), $post_types ) ) { if ( 'related' == $nav_type ) { get_template_part( 'partials/related', 'posts' ); } else { wolf_post_nav(); } } } add_action( 'wolf_post_end', 'wolf_print_post_navigation' ); }
estrategasdigitales/dictobas
wp-content/themes/decibel/includes/actions.php
PHP
gpl-2.0
19,600
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ir.nikagram.messenger.support.widget; import static ir.nikagram.messenger.support.widget.RecyclerView.NO_POSITION; import android.content.Context; import android.graphics.PointF; import android.graphics.Rect; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.view.ViewCompat; import android.support.v4.view.accessibility.AccessibilityEventCompat; import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat; import android.support.v4.view.accessibility.AccessibilityRecordCompat; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.List; /** * A LayoutManager that lays out children in a staggered grid formation. * It supports horizontal & vertical layout as well as an ability to layout children in reverse. * <p> * Staggered grids are likely to have gaps at the edges of the layout. To avoid these gaps, * StaggeredGridLayoutManager can offset spans independently or move items between spans. You can * control this behavior via {@link #setGapStrategy(int)}. */ public class StaggeredGridLayoutManager extends RecyclerView.LayoutManager { public static final String TAG = "StaggeredGridLayoutManager"; private static final boolean DEBUG = false; public static final int HORIZONTAL = OrientationHelper.HORIZONTAL; public static final int VERTICAL = OrientationHelper.VERTICAL; /** * Does not do anything to hide gaps. */ public static final int GAP_HANDLING_NONE = 0; @SuppressWarnings("unused") @Deprecated public static final int GAP_HANDLING_LAZY = 1; /** * When scroll state is changed to {@link RecyclerView#SCROLL_STATE_IDLE}, StaggeredGrid will * check if there are gaps in the because of full span items. If it finds, it will re-layout * and move items to correct positions with animations. * <p> * For example, if LayoutManager ends up with the following layout due to adapter changes: * <pre> * AAA * _BC * DDD * </pre> * <p> * It will animate to the following state: * <pre> * AAA * BC_ * DDD * </pre> */ public static final int GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS = 2; private static final int INVALID_OFFSET = Integer.MIN_VALUE; /** * While trying to find next view to focus, LayoutManager will not try to scroll more * than this factor times the total space of the list. If layout is vertical, total space is the * height minus padding, if layout is horizontal, total space is the width minus padding. */ private static final float MAX_SCROLL_FACTOR = 1 / 3f; /** * Number of spans */ private int mSpanCount = -1; private Span[] mSpans; /** * Primary orientation is the layout's orientation, secondary orientation is the orientation * for spans. Having both makes code much cleaner for calculations. */ @NonNull OrientationHelper mPrimaryOrientation; @NonNull OrientationHelper mSecondaryOrientation; private int mOrientation; /** * The width or height per span, depending on the orientation. */ private int mSizePerSpan; @NonNull private final LayoutState mLayoutState; private boolean mReverseLayout = false; /** * Aggregated reverse layout value that takes RTL into account. */ boolean mShouldReverseLayout = false; /** * Temporary variable used during fill method to check which spans needs to be filled. */ private BitSet mRemainingSpans; /** * When LayoutManager needs to scroll to a position, it sets this variable and requests a * layout which will check this variable and re-layout accordingly. */ int mPendingScrollPosition = NO_POSITION; /** * Used to keep the offset value when {@link #scrollToPositionWithOffset(int, int)} is * called. */ int mPendingScrollPositionOffset = INVALID_OFFSET; /** * Keeps the mapping between the adapter positions and spans. This is necessary to provide * a consistent experience when user scrolls the list. */ LazySpanLookup mLazySpanLookup = new LazySpanLookup(); /** * how we handle gaps in UI. */ private int mGapStrategy = GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS; /** * Saved state needs this information to properly layout on restore. */ private boolean mLastLayoutFromEnd; /** * Saved state and onLayout needs this information to re-layout properly */ private boolean mLastLayoutRTL; /** * SavedState is not handled until a layout happens. This is where we keep it until next * layout. */ private SavedState mPendingSavedState; /** * Re-used measurement specs. updated by onLayout. */ private int mFullSizeSpec; /** * Re-used rectangle to get child decor offsets. */ private final Rect mTmpRect = new Rect(); /** * Re-used anchor info. */ private final AnchorInfo mAnchorInfo = new AnchorInfo(); /** * If a full span item is invalid / or created in reverse direction; it may create gaps in * the UI. While laying out, if such case is detected, we set this flag. * <p> * After scrolling stops, we check this flag and if it is set, re-layout. */ private boolean mLaidOutInvalidFullSpan = false; /** * Works the same way as {@link android.widget.AbsListView#setSmoothScrollbarEnabled(boolean)}. * see {@link android.widget.AbsListView#setSmoothScrollbarEnabled(boolean)} */ private boolean mSmoothScrollbarEnabled = true; private final Runnable mCheckForGapsRunnable = new Runnable() { @Override public void run() { checkForGaps(); } }; /** * Constructor used when layout manager is set in XML by RecyclerView attribute * "layoutManager". Defaults to single column and vertical. */ @SuppressWarnings("unused") public StaggeredGridLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { Properties properties = getProperties(context, attrs, defStyleAttr, defStyleRes); setOrientation(properties.orientation); setSpanCount(properties.spanCount); setReverseLayout(properties.reverseLayout); setAutoMeasureEnabled(mGapStrategy != GAP_HANDLING_NONE); mLayoutState = new LayoutState(); createOrientationHelpers(); } /** * Creates a StaggeredGridLayoutManager with given parameters. * * @param spanCount If orientation is vertical, spanCount is number of columns. If * orientation is horizontal, spanCount is number of rows. * @param orientation {@link #VERTICAL} or {@link #HORIZONTAL} */ public StaggeredGridLayoutManager(int spanCount, int orientation) { mOrientation = orientation; setSpanCount(spanCount); setAutoMeasureEnabled(mGapStrategy != GAP_HANDLING_NONE); mLayoutState = new LayoutState(); createOrientationHelpers(); } private void createOrientationHelpers() { mPrimaryOrientation = OrientationHelper.createOrientationHelper(this, mOrientation); mSecondaryOrientation = OrientationHelper .createOrientationHelper(this, 1 - mOrientation); } /** * Checks for gaps in the UI that may be caused by adapter changes. * <p> * When a full span item is laid out in reverse direction, it sets a flag which we check when * scroll is stopped (or re-layout happens) and re-layout after first valid item. */ private boolean checkForGaps() { if (getChildCount() == 0 || mGapStrategy == GAP_HANDLING_NONE || !isAttachedToWindow()) { return false; } final int minPos, maxPos; if (mShouldReverseLayout) { minPos = getLastChildPosition(); maxPos = getFirstChildPosition(); } else { minPos = getFirstChildPosition(); maxPos = getLastChildPosition(); } if (minPos == 0) { View gapView = hasGapsToFix(); if (gapView != null) { mLazySpanLookup.clear(); requestSimpleAnimationsInNextLayout(); requestLayout(); return true; } } if (!mLaidOutInvalidFullSpan) { return false; } int invalidGapDir = mShouldReverseLayout ? LayoutState.LAYOUT_START : LayoutState.LAYOUT_END; final LazySpanLookup.FullSpanItem invalidFsi = mLazySpanLookup .getFirstFullSpanItemInRange(minPos, maxPos + 1, invalidGapDir, true); if (invalidFsi == null) { mLaidOutInvalidFullSpan = false; mLazySpanLookup.forceInvalidateAfter(maxPos + 1); return false; } final LazySpanLookup.FullSpanItem validFsi = mLazySpanLookup .getFirstFullSpanItemInRange(minPos, invalidFsi.mPosition, invalidGapDir * -1, true); if (validFsi == null) { mLazySpanLookup.forceInvalidateAfter(invalidFsi.mPosition); } else { mLazySpanLookup.forceInvalidateAfter(validFsi.mPosition + 1); } requestSimpleAnimationsInNextLayout(); requestLayout(); return true; } @Override public void onScrollStateChanged(int state) { if (state == RecyclerView.SCROLL_STATE_IDLE) { checkForGaps(); } } @Override public void onDetachedFromWindow(RecyclerView view, RecyclerView.Recycler recycler) { removeCallbacks(mCheckForGapsRunnable); for (int i = 0; i < mSpanCount; i++) { mSpans[i].clear(); } } /** * Checks for gaps if we've reached to the top of the list. * <p> * Intermediate gaps created by full span items are tracked via mLaidOutInvalidFullSpan field. */ View hasGapsToFix() { int startChildIndex = 0; int endChildIndex = getChildCount() - 1; BitSet mSpansToCheck = new BitSet(mSpanCount); mSpansToCheck.set(0, mSpanCount, true); final int firstChildIndex, childLimit; final int preferredSpanDir = mOrientation == VERTICAL && isLayoutRTL() ? 1 : -1; if (mShouldReverseLayout) { firstChildIndex = endChildIndex; childLimit = startChildIndex - 1; } else { firstChildIndex = startChildIndex; childLimit = endChildIndex + 1; } final int nextChildDiff = firstChildIndex < childLimit ? 1 : -1; for (int i = firstChildIndex; i != childLimit; i += nextChildDiff) { View child = getChildAt(i); LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (mSpansToCheck.get(lp.mSpan.mIndex)) { if (checkSpanForGap(lp.mSpan)) { return child; } mSpansToCheck.clear(lp.mSpan.mIndex); } if (lp.mFullSpan) { continue; // quick reject } if (i + nextChildDiff != childLimit) { View nextChild = getChildAt(i + nextChildDiff); boolean compareSpans = false; if (mShouldReverseLayout) { // ensure child's end is below nextChild's end int myEnd = mPrimaryOrientation.getDecoratedEnd(child); int nextEnd = mPrimaryOrientation.getDecoratedEnd(nextChild); if (myEnd < nextEnd) { return child;//i should have a better position } else if (myEnd == nextEnd) { compareSpans = true; } } else { int myStart = mPrimaryOrientation.getDecoratedStart(child); int nextStart = mPrimaryOrientation.getDecoratedStart(nextChild); if (myStart > nextStart) { return child;//i should have a better position } else if (myStart == nextStart) { compareSpans = true; } } if (compareSpans) { // equal, check span indices. LayoutParams nextLp = (LayoutParams) nextChild.getLayoutParams(); if (lp.mSpan.mIndex - nextLp.mSpan.mIndex < 0 != preferredSpanDir < 0) { return child; } } } } // everything looks good return null; } private boolean checkSpanForGap(Span span) { if (mShouldReverseLayout) { if (span.getEndLine() < mPrimaryOrientation.getEndAfterPadding()) { // if it is full span, it is OK final View endView = span.mViews.get(span.mViews.size() - 1); final LayoutParams lp = span.getLayoutParams(endView); return !lp.mFullSpan; } } else if (span.getStartLine() > mPrimaryOrientation.getStartAfterPadding()) { // if it is full span, it is OK final View startView = span.mViews.get(0); final LayoutParams lp = span.getLayoutParams(startView); return !lp.mFullSpan; } return false; } /** * Sets the number of spans for the layout. This will invalidate all of the span assignments * for Views. * <p> * Calling this method will automatically result in a new layout request unless the spanCount * parameter is equal to current span count. * * @param spanCount Number of spans to layout */ public void setSpanCount(int spanCount) { assertNotInLayoutOrScroll(null); if (spanCount != mSpanCount) { invalidateSpanAssignments(); mSpanCount = spanCount; mRemainingSpans = new BitSet(mSpanCount); mSpans = new Span[mSpanCount]; for (int i = 0; i < mSpanCount; i++) { mSpans[i] = new Span(i); } requestLayout(); } } /** * Sets the orientation of the layout. StaggeredGridLayoutManager will do its best to keep * scroll position if this method is called after views are laid out. * * @param orientation {@link #HORIZONTAL} or {@link #VERTICAL} */ public void setOrientation(int orientation) { if (orientation != HORIZONTAL && orientation != VERTICAL) { throw new IllegalArgumentException("invalid orientation."); } assertNotInLayoutOrScroll(null); if (orientation == mOrientation) { return; } mOrientation = orientation; OrientationHelper tmp = mPrimaryOrientation; mPrimaryOrientation = mSecondaryOrientation; mSecondaryOrientation = tmp; requestLayout(); } /** * Sets whether LayoutManager should start laying out items from the end of the UI. The order * items are traversed is not affected by this call. * <p> * For vertical layout, if it is set to <code>true</code>, first item will be at the bottom of * the list. * <p> * For horizontal layouts, it depends on the layout direction. * When set to true, If {@link RecyclerView} is LTR, than it will layout from RTL, if * {@link RecyclerView}} is RTL, it will layout from LTR. * * @param reverseLayout Whether layout should be in reverse or not */ public void setReverseLayout(boolean reverseLayout) { assertNotInLayoutOrScroll(null); if (mPendingSavedState != null && mPendingSavedState.mReverseLayout != reverseLayout) { mPendingSavedState.mReverseLayout = reverseLayout; } mReverseLayout = reverseLayout; requestLayout(); } /** * Returns the current gap handling strategy for StaggeredGridLayoutManager. * <p> * Staggered grid may have gaps in the layout due to changes in the adapter. To avoid gaps, * StaggeredGridLayoutManager provides 2 options. Check {@link #GAP_HANDLING_NONE} and * {@link #GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS} for details. * <p> * By default, StaggeredGridLayoutManager uses {@link #GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS}. * * @return Current gap handling strategy. * @see #setGapStrategy(int) * @see #GAP_HANDLING_NONE * @see #GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS */ public int getGapStrategy() { return mGapStrategy; } /** * Sets the gap handling strategy for StaggeredGridLayoutManager. If the gapStrategy parameter * is different than the current strategy, calling this method will trigger a layout request. * * @param gapStrategy The new gap handling strategy. Should be * {@link #GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS} or {@link * #GAP_HANDLING_NONE}. * @see #getGapStrategy() */ public void setGapStrategy(int gapStrategy) { assertNotInLayoutOrScroll(null); if (gapStrategy == mGapStrategy) { return; } if (gapStrategy != GAP_HANDLING_NONE && gapStrategy != GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS) { throw new IllegalArgumentException("invalid gap strategy. Must be GAP_HANDLING_NONE " + "or GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS"); } mGapStrategy = gapStrategy; setAutoMeasureEnabled(mGapStrategy != GAP_HANDLING_NONE); requestLayout(); } @Override public void assertNotInLayoutOrScroll(String message) { if (mPendingSavedState == null) { super.assertNotInLayoutOrScroll(message); } } /** * Returns the number of spans laid out by StaggeredGridLayoutManager. * * @return Number of spans in the layout */ public int getSpanCount() { return mSpanCount; } /** * For consistency, StaggeredGridLayoutManager keeps a mapping between spans and items. * <p> * If you need to cancel current assignments, you can call this method which will clear all * assignments and request a new layout. */ public void invalidateSpanAssignments() { mLazySpanLookup.clear(); requestLayout(); } /** * Calculates the views' layout order. (e.g. from end to start or start to end) * RTL layout support is applied automatically. So if layout is RTL and * {@link #getReverseLayout()} is {@code true}, elements will be laid out starting from left. */ private void resolveShouldLayoutReverse() { // A == B is the same result, but we rather keep it readable if (mOrientation == VERTICAL || !isLayoutRTL()) { mShouldReverseLayout = mReverseLayout; } else { mShouldReverseLayout = !mReverseLayout; } } boolean isLayoutRTL() { return getLayoutDirection() == ViewCompat.LAYOUT_DIRECTION_RTL; } /** * Returns whether views are laid out in reverse order or not. * <p> * Not that this value is not affected by RecyclerView's layout direction. * * @return True if layout is reversed, false otherwise * @see #setReverseLayout(boolean) */ public boolean getReverseLayout() { return mReverseLayout; } @Override public void setMeasuredDimension(Rect childrenBounds, int wSpec, int hSpec) { // we don't like it to wrap content in our non-scroll direction. final int width, height; final int horizontalPadding = getPaddingLeft() + getPaddingRight(); final int verticalPadding = getPaddingTop() + getPaddingBottom(); if (mOrientation == VERTICAL) { final int usedHeight = childrenBounds.height() + verticalPadding; height = chooseSize(hSpec, usedHeight, getMinimumHeight()); width = chooseSize(wSpec, mSizePerSpan * mSpanCount + horizontalPadding, getMinimumWidth()); } else { final int usedWidth = childrenBounds.width() + horizontalPadding; width = chooseSize(wSpec, usedWidth, getMinimumWidth()); height = chooseSize(hSpec, mSizePerSpan * mSpanCount + verticalPadding, getMinimumHeight()); } setMeasuredDimension(width, height); } @Override public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) { onLayoutChildren(recycler, state, true); } private void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state, boolean shouldCheckForGaps) { final AnchorInfo anchorInfo = mAnchorInfo; anchorInfo.reset(); if (mPendingSavedState != null || mPendingScrollPosition != NO_POSITION) { if (state.getItemCount() == 0) { removeAndRecycleAllViews(recycler); return; } } if (mPendingSavedState != null) { applyPendingSavedState(anchorInfo); } else { resolveShouldLayoutReverse(); anchorInfo.mLayoutFromEnd = mShouldReverseLayout; } updateAnchorInfoForLayout(state, anchorInfo); if (mPendingSavedState == null) { if (anchorInfo.mLayoutFromEnd != mLastLayoutFromEnd || isLayoutRTL() != mLastLayoutRTL) { mLazySpanLookup.clear(); anchorInfo.mInvalidateOffsets = true; } } if (getChildCount() > 0 && (mPendingSavedState == null || mPendingSavedState.mSpanOffsetsSize < 1)) { if (anchorInfo.mInvalidateOffsets) { for (int i = 0; i < mSpanCount; i++) { // Scroll to position is set, clear. mSpans[i].clear(); if (anchorInfo.mOffset != INVALID_OFFSET) { mSpans[i].setLine(anchorInfo.mOffset); } } } else { for (int i = 0; i < mSpanCount; i++) { mSpans[i].cacheReferenceLineAndClear(mShouldReverseLayout, anchorInfo.mOffset); } } } detachAndScrapAttachedViews(recycler); mLayoutState.mRecycle = false; mLaidOutInvalidFullSpan = false; updateMeasureSpecs(mSecondaryOrientation.getTotalSpace()); updateLayoutState(anchorInfo.mPosition, state); if (anchorInfo.mLayoutFromEnd) { // Layout start. setLayoutStateDirection(LayoutState.LAYOUT_START); fill(recycler, mLayoutState, state); // Layout end. setLayoutStateDirection(LayoutState.LAYOUT_END); mLayoutState.mCurrentPosition = anchorInfo.mPosition + mLayoutState.mItemDirection; fill(recycler, mLayoutState, state); } else { // Layout end. setLayoutStateDirection(LayoutState.LAYOUT_END); fill(recycler, mLayoutState, state); // Layout start. setLayoutStateDirection(LayoutState.LAYOUT_START); mLayoutState.mCurrentPosition = anchorInfo.mPosition + mLayoutState.mItemDirection; fill(recycler, mLayoutState, state); } repositionToWrapContentIfNecessary(); if (getChildCount() > 0) { if (mShouldReverseLayout) { fixEndGap(recycler, state, true); fixStartGap(recycler, state, false); } else { fixStartGap(recycler, state, true); fixEndGap(recycler, state, false); } } boolean hasGaps = false; if (shouldCheckForGaps && !state.isPreLayout()) { final boolean needToCheckForGaps = mGapStrategy != GAP_HANDLING_NONE && getChildCount() > 0 && (mLaidOutInvalidFullSpan || hasGapsToFix() != null); if (needToCheckForGaps) { removeCallbacks(mCheckForGapsRunnable); if (checkForGaps()) { hasGaps = true; } } mPendingScrollPosition = NO_POSITION; mPendingScrollPositionOffset = INVALID_OFFSET; } mLastLayoutFromEnd = anchorInfo.mLayoutFromEnd; mLastLayoutRTL = isLayoutRTL(); mPendingSavedState = null; // we don't need this anymore if (hasGaps) { onLayoutChildren(recycler, state, false); } } private void repositionToWrapContentIfNecessary() { if (mSecondaryOrientation.getMode() == View.MeasureSpec.EXACTLY) { return; // nothing to do } float maxSize = 0; final int childCount = getChildCount(); for (int i = 0; i < childCount; i ++) { View child = getChildAt(i); float size = mSecondaryOrientation.getDecoratedMeasurement(child); if (size < maxSize) { continue; } LayoutParams layoutParams = (LayoutParams) child.getLayoutParams(); if (layoutParams.isFullSpan()) { size = 1f * size / mSpanCount; } maxSize = Math.max(maxSize, size); } int before = mSizePerSpan; int desired = Math.round(maxSize * mSpanCount); if (mSecondaryOrientation.getMode() == View.MeasureSpec.AT_MOST) { desired = Math.min(desired, mSecondaryOrientation.getTotalSpace()); } updateMeasureSpecs(desired); if (mSizePerSpan == before) { return; // nothing has changed } for (int i = 0; i < childCount; i ++) { View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp.mFullSpan) { continue; } if (isLayoutRTL() && mOrientation == VERTICAL) { int newOffset = -(mSpanCount - 1 - lp.mSpan.mIndex) * mSizePerSpan; int prevOffset = -(mSpanCount - 1 - lp.mSpan.mIndex) * before; child.offsetLeftAndRight(newOffset - prevOffset); } else { int newOffset = lp.mSpan.mIndex * mSizePerSpan; int prevOffset = lp.mSpan.mIndex * before; if (mOrientation == VERTICAL) { child.offsetLeftAndRight(newOffset - prevOffset); } else { child.offsetTopAndBottom(newOffset - prevOffset); } } } } private void applyPendingSavedState(AnchorInfo anchorInfo) { if (DEBUG) { Log.d(TAG, "found saved state: " + mPendingSavedState); } if (mPendingSavedState.mSpanOffsetsSize > 0) { if (mPendingSavedState.mSpanOffsetsSize == mSpanCount) { for (int i = 0; i < mSpanCount; i++) { mSpans[i].clear(); int line = mPendingSavedState.mSpanOffsets[i]; if (line != Span.INVALID_LINE) { if (mPendingSavedState.mAnchorLayoutFromEnd) { line += mPrimaryOrientation.getEndAfterPadding(); } else { line += mPrimaryOrientation.getStartAfterPadding(); } } mSpans[i].setLine(line); } } else { mPendingSavedState.invalidateSpanInfo(); mPendingSavedState.mAnchorPosition = mPendingSavedState.mVisibleAnchorPosition; } } mLastLayoutRTL = mPendingSavedState.mLastLayoutRTL; setReverseLayout(mPendingSavedState.mReverseLayout); resolveShouldLayoutReverse(); if (mPendingSavedState.mAnchorPosition != NO_POSITION) { mPendingScrollPosition = mPendingSavedState.mAnchorPosition; anchorInfo.mLayoutFromEnd = mPendingSavedState.mAnchorLayoutFromEnd; } else { anchorInfo.mLayoutFromEnd = mShouldReverseLayout; } if (mPendingSavedState.mSpanLookupSize > 1) { mLazySpanLookup.mData = mPendingSavedState.mSpanLookup; mLazySpanLookup.mFullSpanItems = mPendingSavedState.mFullSpanItems; } } void updateAnchorInfoForLayout(RecyclerView.State state, AnchorInfo anchorInfo) { if (updateAnchorFromPendingData(state, anchorInfo)) { return; } if (updateAnchorFromChildren(state, anchorInfo)) { return; } if (DEBUG) { Log.d(TAG, "Deciding anchor info from fresh state"); } anchorInfo.assignCoordinateFromPadding(); anchorInfo.mPosition = 0; } private boolean updateAnchorFromChildren(RecyclerView.State state, AnchorInfo anchorInfo) { // We don't recycle views out of adapter order. This way, we can rely on the first or // last child as the anchor position. // Layout direction may change but we should select the child depending on the latest // layout direction. Otherwise, we'll choose the wrong child. anchorInfo.mPosition = mLastLayoutFromEnd ? findLastReferenceChildPosition(state.getItemCount()) : findFirstReferenceChildPosition(state.getItemCount()); anchorInfo.mOffset = INVALID_OFFSET; return true; } boolean updateAnchorFromPendingData(RecyclerView.State state, AnchorInfo anchorInfo) { // Validate scroll position if exists. if (state.isPreLayout() || mPendingScrollPosition == NO_POSITION) { return false; } // Validate it. if (mPendingScrollPosition < 0 || mPendingScrollPosition >= state.getItemCount()) { mPendingScrollPosition = NO_POSITION; mPendingScrollPositionOffset = INVALID_OFFSET; return false; } if (mPendingSavedState == null || mPendingSavedState.mAnchorPosition == NO_POSITION || mPendingSavedState.mSpanOffsetsSize < 1) { // If item is visible, make it fully visible. final View child = findViewByPosition(mPendingScrollPosition); if (child != null) { // Use regular anchor position, offset according to pending offset and target // child anchorInfo.mPosition = mShouldReverseLayout ? getLastChildPosition() : getFirstChildPosition(); if (mPendingScrollPositionOffset != INVALID_OFFSET) { if (anchorInfo.mLayoutFromEnd) { final int target = mPrimaryOrientation.getEndAfterPadding() - mPendingScrollPositionOffset; anchorInfo.mOffset = target - mPrimaryOrientation.getDecoratedEnd(child); } else { final int target = mPrimaryOrientation.getStartAfterPadding() + mPendingScrollPositionOffset; anchorInfo.mOffset = target - mPrimaryOrientation.getDecoratedStart(child); } return true; } // no offset provided. Decide according to the child location final int childSize = mPrimaryOrientation.getDecoratedMeasurement(child); if (childSize > mPrimaryOrientation.getTotalSpace()) { // Item does not fit. Fix depending on layout direction. anchorInfo.mOffset = anchorInfo.mLayoutFromEnd ? mPrimaryOrientation.getEndAfterPadding() : mPrimaryOrientation.getStartAfterPadding(); return true; } final int startGap = mPrimaryOrientation.getDecoratedStart(child) - mPrimaryOrientation.getStartAfterPadding(); if (startGap < 0) { anchorInfo.mOffset = -startGap; return true; } final int endGap = mPrimaryOrientation.getEndAfterPadding() - mPrimaryOrientation.getDecoratedEnd(child); if (endGap < 0) { anchorInfo.mOffset = endGap; return true; } // child already visible. just layout as usual anchorInfo.mOffset = INVALID_OFFSET; } else { // Child is not visible. Set anchor coordinate depending on in which direction // child will be visible. anchorInfo.mPosition = mPendingScrollPosition; if (mPendingScrollPositionOffset == INVALID_OFFSET) { final int position = calculateScrollDirectionForPosition( anchorInfo.mPosition); anchorInfo.mLayoutFromEnd = position == LayoutState.LAYOUT_END; anchorInfo.assignCoordinateFromPadding(); } else { anchorInfo.assignCoordinateFromPadding(mPendingScrollPositionOffset); } anchorInfo.mInvalidateOffsets = true; } } else { anchorInfo.mOffset = INVALID_OFFSET; anchorInfo.mPosition = mPendingScrollPosition; } return true; } void updateMeasureSpecs(int totalSpace) { mSizePerSpan = totalSpace / mSpanCount; //noinspection ResourceType mFullSizeSpec = View.MeasureSpec.makeMeasureSpec( totalSpace, mSecondaryOrientation.getMode()); } @Override public boolean supportsPredictiveItemAnimations() { return mPendingSavedState == null; } /** * Returns the adapter position of the first visible view for each span. * <p> * Note that, this value is not affected by layout orientation or item order traversal. * ({@link #setReverseLayout(boolean)}). Views are sorted by their positions in the adapter, * not in the layout. * <p> * If RecyclerView has item decorators, they will be considered in calculations as well. * <p> * StaggeredGridLayoutManager may pre-cache some views that are not necessarily visible. Those * views are ignored in this method. * * @param into An array to put the results into. If you don't provide any, LayoutManager will * create a new one. * @return The adapter position of the first visible item in each span. If a span does not have * any items, {@link RecyclerView#NO_POSITION} is returned for that span. * @see #findFirstCompletelyVisibleItemPositions(int[]) * @see #findLastVisibleItemPositions(int[]) */ public int[] findFirstVisibleItemPositions(int[] into) { if (into == null) { into = new int[mSpanCount]; } else if (into.length < mSpanCount) { throw new IllegalArgumentException("Provided int[]'s size must be more than or equal" + " to span count. Expected:" + mSpanCount + ", array size:" + into.length); } for (int i = 0; i < mSpanCount; i++) { into[i] = mSpans[i].findFirstVisibleItemPosition(); } return into; } /** * Returns the adapter position of the first completely visible view for each span. * <p> * Note that, this value is not affected by layout orientation or item order traversal. * ({@link #setReverseLayout(boolean)}). Views are sorted by their positions in the adapter, * not in the layout. * <p> * If RecyclerView has item decorators, they will be considered in calculations as well. * <p> * StaggeredGridLayoutManager may pre-cache some views that are not necessarily visible. Those * views are ignored in this method. * * @param into An array to put the results into. If you don't provide any, LayoutManager will * create a new one. * @return The adapter position of the first fully visible item in each span. If a span does * not have any items, {@link RecyclerView#NO_POSITION} is returned for that span. * @see #findFirstVisibleItemPositions(int[]) * @see #findLastCompletelyVisibleItemPositions(int[]) */ public int[] findFirstCompletelyVisibleItemPositions(int[] into) { if (into == null) { into = new int[mSpanCount]; } else if (into.length < mSpanCount) { throw new IllegalArgumentException("Provided int[]'s size must be more than or equal" + " to span count. Expected:" + mSpanCount + ", array size:" + into.length); } for (int i = 0; i < mSpanCount; i++) { into[i] = mSpans[i].findFirstCompletelyVisibleItemPosition(); } return into; } /** * Returns the adapter position of the last visible view for each span. * <p> * Note that, this value is not affected by layout orientation or item order traversal. * ({@link #setReverseLayout(boolean)}). Views are sorted by their positions in the adapter, * not in the layout. * <p> * If RecyclerView has item decorators, they will be considered in calculations as well. * <p> * StaggeredGridLayoutManager may pre-cache some views that are not necessarily visible. Those * views are ignored in this method. * * @param into An array to put the results into. If you don't provide any, LayoutManager will * create a new one. * @return The adapter position of the last visible item in each span. If a span does not have * any items, {@link RecyclerView#NO_POSITION} is returned for that span. * @see #findLastCompletelyVisibleItemPositions(int[]) * @see #findFirstVisibleItemPositions(int[]) */ public int[] findLastVisibleItemPositions(int[] into) { if (into == null) { into = new int[mSpanCount]; } else if (into.length < mSpanCount) { throw new IllegalArgumentException("Provided int[]'s size must be more than or equal" + " to span count. Expected:" + mSpanCount + ", array size:" + into.length); } for (int i = 0; i < mSpanCount; i++) { into[i] = mSpans[i].findLastVisibleItemPosition(); } return into; } /** * Returns the adapter position of the last completely visible view for each span. * <p> * Note that, this value is not affected by layout orientation or item order traversal. * ({@link #setReverseLayout(boolean)}). Views are sorted by their positions in the adapter, * not in the layout. * <p> * If RecyclerView has item decorators, they will be considered in calculations as well. * <p> * StaggeredGridLayoutManager may pre-cache some views that are not necessarily visible. Those * views are ignored in this method. * * @param into An array to put the results into. If you don't provide any, LayoutManager will * create a new one. * @return The adapter position of the last fully visible item in each span. If a span does not * have any items, {@link RecyclerView#NO_POSITION} is returned for that span. * @see #findFirstCompletelyVisibleItemPositions(int[]) * @see #findLastVisibleItemPositions(int[]) */ public int[] findLastCompletelyVisibleItemPositions(int[] into) { if (into == null) { into = new int[mSpanCount]; } else if (into.length < mSpanCount) { throw new IllegalArgumentException("Provided int[]'s size must be more than or equal" + " to span count. Expected:" + mSpanCount + ", array size:" + into.length); } for (int i = 0; i < mSpanCount; i++) { into[i] = mSpans[i].findLastCompletelyVisibleItemPosition(); } return into; } @Override public int computeHorizontalScrollOffset(RecyclerView.State state) { return computeScrollOffset(state); } private int computeScrollOffset(RecyclerView.State state) { if (getChildCount() == 0) { return 0; } return ScrollbarHelper.computeScrollOffset(state, mPrimaryOrientation, findFirstVisibleItemClosestToStart(!mSmoothScrollbarEnabled, true) , findFirstVisibleItemClosestToEnd(!mSmoothScrollbarEnabled, true), this, mSmoothScrollbarEnabled, mShouldReverseLayout); } @Override public int computeVerticalScrollOffset(RecyclerView.State state) { return computeScrollOffset(state); } @Override public int computeHorizontalScrollExtent(RecyclerView.State state) { return computeScrollExtent(state); } private int computeScrollExtent(RecyclerView.State state) { if (getChildCount() == 0) { return 0; } return ScrollbarHelper.computeScrollExtent(state, mPrimaryOrientation, findFirstVisibleItemClosestToStart(!mSmoothScrollbarEnabled, true) , findFirstVisibleItemClosestToEnd(!mSmoothScrollbarEnabled, true), this, mSmoothScrollbarEnabled); } @Override public int computeVerticalScrollExtent(RecyclerView.State state) { return computeScrollExtent(state); } @Override public int computeHorizontalScrollRange(RecyclerView.State state) { return computeScrollRange(state); } private int computeScrollRange(RecyclerView.State state) { if (getChildCount() == 0) { return 0; } return ScrollbarHelper.computeScrollRange(state, mPrimaryOrientation, findFirstVisibleItemClosestToStart(!mSmoothScrollbarEnabled, true) , findFirstVisibleItemClosestToEnd(!mSmoothScrollbarEnabled, true), this, mSmoothScrollbarEnabled); } @Override public int computeVerticalScrollRange(RecyclerView.State state) { return computeScrollRange(state); } private void measureChildWithDecorationsAndMargin(View child, LayoutParams lp, boolean alreadyMeasured) { if (lp.mFullSpan) { if (mOrientation == VERTICAL) { measureChildWithDecorationsAndMargin(child, mFullSizeSpec, getChildMeasureSpec(getHeight(), getHeightMode(), 0, lp.height, true), alreadyMeasured); } else { measureChildWithDecorationsAndMargin(child, getChildMeasureSpec(getWidth(), getWidthMode(), 0, lp.width, true), mFullSizeSpec, alreadyMeasured); } } else { if (mOrientation == VERTICAL) { measureChildWithDecorationsAndMargin(child, getChildMeasureSpec(mSizePerSpan, getWidthMode(), 0, lp.width, false), getChildMeasureSpec(getHeight(), getHeightMode(), 0, lp.height, true), alreadyMeasured); } else { measureChildWithDecorationsAndMargin(child, getChildMeasureSpec(getWidth(), getWidthMode(), 0, lp.width, true), getChildMeasureSpec(mSizePerSpan, getHeightMode(), 0, lp.height, false), alreadyMeasured); } } } private void measureChildWithDecorationsAndMargin(View child, int widthSpec, int heightSpec, boolean alreadyMeasured) { calculateItemDecorationsForChild(child, mTmpRect); LayoutParams lp = (LayoutParams) child.getLayoutParams(); widthSpec = updateSpecWithExtra(widthSpec, lp.leftMargin + mTmpRect.left, lp.rightMargin + mTmpRect.right); heightSpec = updateSpecWithExtra(heightSpec, lp.topMargin + mTmpRect.top, lp.bottomMargin + mTmpRect.bottom); final boolean measure = alreadyMeasured ? shouldReMeasureChild(child, widthSpec, heightSpec, lp) : shouldMeasureChild(child, widthSpec, heightSpec, lp); if (measure) { child.measure(widthSpec, heightSpec); } } private int updateSpecWithExtra(int spec, int startInset, int endInset) { if (startInset == 0 && endInset == 0) { return spec; } final int mode = View.MeasureSpec.getMode(spec); if (mode == View.MeasureSpec.AT_MOST || mode == View.MeasureSpec.EXACTLY) { return View.MeasureSpec.makeMeasureSpec( Math.max(0, View.MeasureSpec.getSize(spec) - startInset - endInset), mode); } return spec; } @Override public void onRestoreInstanceState(Parcelable state) { if (state instanceof SavedState) { mPendingSavedState = (SavedState) state; requestLayout(); } else if (DEBUG) { Log.d(TAG, "invalid saved state class"); } } @Override public Parcelable onSaveInstanceState() { if (mPendingSavedState != null) { return new SavedState(mPendingSavedState); } SavedState state = new SavedState(); state.mReverseLayout = mReverseLayout; state.mAnchorLayoutFromEnd = mLastLayoutFromEnd; state.mLastLayoutRTL = mLastLayoutRTL; if (mLazySpanLookup != null && mLazySpanLookup.mData != null) { state.mSpanLookup = mLazySpanLookup.mData; state.mSpanLookupSize = state.mSpanLookup.length; state.mFullSpanItems = mLazySpanLookup.mFullSpanItems; } else { state.mSpanLookupSize = 0; } if (getChildCount() > 0) { state.mAnchorPosition = mLastLayoutFromEnd ? getLastChildPosition() : getFirstChildPosition(); state.mVisibleAnchorPosition = findFirstVisibleItemPositionInt(); state.mSpanOffsetsSize = mSpanCount; state.mSpanOffsets = new int[mSpanCount]; for (int i = 0; i < mSpanCount; i++) { int line; if (mLastLayoutFromEnd) { line = mSpans[i].getEndLine(Span.INVALID_LINE); if (line != Span.INVALID_LINE) { line -= mPrimaryOrientation.getEndAfterPadding(); } } else { line = mSpans[i].getStartLine(Span.INVALID_LINE); if (line != Span.INVALID_LINE) { line -= mPrimaryOrientation.getStartAfterPadding(); } } state.mSpanOffsets[i] = line; } } else { state.mAnchorPosition = NO_POSITION; state.mVisibleAnchorPosition = NO_POSITION; state.mSpanOffsetsSize = 0; } if (DEBUG) { Log.d(TAG, "saved state:\n" + state); } return state; } @Override public void onInitializeAccessibilityNodeInfoForItem(RecyclerView.Recycler recycler, RecyclerView.State state, View host, AccessibilityNodeInfoCompat info) { ViewGroup.LayoutParams lp = host.getLayoutParams(); if (!(lp instanceof LayoutParams)) { super.onInitializeAccessibilityNodeInfoForItem(host, info); return; } LayoutParams sglp = (LayoutParams) lp; if (mOrientation == HORIZONTAL) { info.setCollectionItemInfo(AccessibilityNodeInfoCompat.CollectionItemInfoCompat.obtain( sglp.getSpanIndex(), sglp.mFullSpan ? mSpanCount : 1, -1, -1, sglp.mFullSpan, false)); } else { // VERTICAL info.setCollectionItemInfo(AccessibilityNodeInfoCompat.CollectionItemInfoCompat.obtain( -1, -1, sglp.getSpanIndex(), sglp.mFullSpan ? mSpanCount : 1, sglp.mFullSpan, false)); } } @Override public void onInitializeAccessibilityEvent(AccessibilityEvent event) { super.onInitializeAccessibilityEvent(event); if (getChildCount() > 0) { final AccessibilityRecordCompat record = AccessibilityEventCompat .asRecord(event); final View start = findFirstVisibleItemClosestToStart(false, true); final View end = findFirstVisibleItemClosestToEnd(false, true); if (start == null || end == null) { return; } final int startPos = getPosition(start); final int endPos = getPosition(end); if (startPos < endPos) { record.setFromIndex(startPos); record.setToIndex(endPos); } else { record.setFromIndex(endPos); record.setToIndex(startPos); } } } /** * Finds the first fully visible child to be used as an anchor child if span count changes when * state is restored. If no children is fully visible, returns a partially visible child instead * of returning null. */ int findFirstVisibleItemPositionInt() { final View first = mShouldReverseLayout ? findFirstVisibleItemClosestToEnd(true, true) : findFirstVisibleItemClosestToStart(true, true); return first == null ? NO_POSITION : getPosition(first); } @Override public int getRowCountForAccessibility(RecyclerView.Recycler recycler, RecyclerView.State state) { if (mOrientation == HORIZONTAL) { return mSpanCount; } return super.getRowCountForAccessibility(recycler, state); } @Override public int getColumnCountForAccessibility(RecyclerView.Recycler recycler, RecyclerView.State state) { if (mOrientation == VERTICAL) { return mSpanCount; } return super.getColumnCountForAccessibility(recycler, state); } /** * This is for internal use. Not necessarily the child closest to start but the first child * we find that matches the criteria. * This method does not do any sorting based on child's start coordinate, instead, it uses * children order. */ View findFirstVisibleItemClosestToStart(boolean fullyVisible, boolean acceptPartiallyVisible) { final int boundsStart = mPrimaryOrientation.getStartAfterPadding(); final int boundsEnd = mPrimaryOrientation.getEndAfterPadding(); final int limit = getChildCount(); View partiallyVisible = null; for (int i = 0; i < limit; i++) { final View child = getChildAt(i); final int childStart = mPrimaryOrientation.getDecoratedStart(child); final int childEnd = mPrimaryOrientation.getDecoratedEnd(child); if(childEnd <= boundsStart || childStart >= boundsEnd) { continue; // not visible at all } if (childStart >= boundsStart || !fullyVisible) { // when checking for start, it is enough even if part of the child's top is visible // as long as fully visible is not requested. return child; } if (acceptPartiallyVisible && partiallyVisible == null) { partiallyVisible = child; } } return partiallyVisible; } /** * This is for internal use. Not necessarily the child closest to bottom but the first child * we find that matches the criteria. * This method does not do any sorting based on child's end coordinate, instead, it uses * children order. */ View findFirstVisibleItemClosestToEnd(boolean fullyVisible, boolean acceptPartiallyVisible) { final int boundsStart = mPrimaryOrientation.getStartAfterPadding(); final int boundsEnd = mPrimaryOrientation.getEndAfterPadding(); View partiallyVisible = null; for (int i = getChildCount() - 1; i >= 0; i--) { final View child = getChildAt(i); final int childStart = mPrimaryOrientation.getDecoratedStart(child); final int childEnd = mPrimaryOrientation.getDecoratedEnd(child); if(childEnd <= boundsStart || childStart >= boundsEnd) { continue; // not visible at all } if (childEnd <= boundsEnd || !fullyVisible) { // when checking for end, it is enough even if part of the child's bottom is visible // as long as fully visible is not requested. return child; } if (acceptPartiallyVisible && partiallyVisible == null) { partiallyVisible = child; } } return partiallyVisible; } private void fixEndGap(RecyclerView.Recycler recycler, RecyclerView.State state, boolean canOffsetChildren) { final int maxEndLine = getMaxEnd(Integer.MIN_VALUE); if (maxEndLine == Integer.MIN_VALUE) { return; } int gap = mPrimaryOrientation.getEndAfterPadding() - maxEndLine; int fixOffset; if (gap > 0) { fixOffset = -scrollBy(-gap, recycler, state); } else { return; // nothing to fix } gap -= fixOffset; if (canOffsetChildren && gap > 0) { mPrimaryOrientation.offsetChildren(gap); } } private void fixStartGap(RecyclerView.Recycler recycler, RecyclerView.State state, boolean canOffsetChildren) { final int minStartLine = getMinStart(Integer.MAX_VALUE); if (minStartLine == Integer.MAX_VALUE) { return; } int gap = minStartLine - mPrimaryOrientation.getStartAfterPadding(); int fixOffset; if (gap > 0) { fixOffset = scrollBy(gap, recycler, state); } else { return; // nothing to fix } gap -= fixOffset; if (canOffsetChildren && gap > 0) { mPrimaryOrientation.offsetChildren(-gap); } } private void updateLayoutState(int anchorPosition, RecyclerView.State state) { mLayoutState.mAvailable = 0; mLayoutState.mCurrentPosition = anchorPosition; int startExtra = 0; int endExtra = 0; if (isSmoothScrolling()) { final int targetPos = state.getTargetScrollPosition(); if (targetPos != NO_POSITION) { if (mShouldReverseLayout == targetPos < anchorPosition) { endExtra = mPrimaryOrientation.getTotalSpace(); } else { startExtra = mPrimaryOrientation.getTotalSpace(); } } } // Line of the furthest row. final boolean clipToPadding = getClipToPadding(); if (clipToPadding) { mLayoutState.mStartLine = mPrimaryOrientation.getStartAfterPadding() - startExtra; mLayoutState.mEndLine = mPrimaryOrientation.getEndAfterPadding() + endExtra; } else { mLayoutState.mEndLine = mPrimaryOrientation.getEnd() + endExtra; mLayoutState.mStartLine = -startExtra; } mLayoutState.mStopInFocusable = false; mLayoutState.mRecycle = true; mLayoutState.mInfinite = mPrimaryOrientation.getMode() == View.MeasureSpec.UNSPECIFIED && mPrimaryOrientation.getEnd() == 0; } private void setLayoutStateDirection(int direction) { mLayoutState.mLayoutDirection = direction; mLayoutState.mItemDirection = (mShouldReverseLayout == (direction == LayoutState.LAYOUT_START)) ? LayoutState.ITEM_DIRECTION_TAIL : LayoutState.ITEM_DIRECTION_HEAD; } @Override public void offsetChildrenHorizontal(int dx) { super.offsetChildrenHorizontal(dx); for (int i = 0; i < mSpanCount; i++) { mSpans[i].onOffset(dx); } } @Override public void offsetChildrenVertical(int dy) { super.offsetChildrenVertical(dy); for (int i = 0; i < mSpanCount; i++) { mSpans[i].onOffset(dy); } } @Override public void onItemsRemoved(RecyclerView recyclerView, int positionStart, int itemCount) { handleUpdate(positionStart, itemCount, AdapterHelper.UpdateOp.REMOVE); } @Override public void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount) { handleUpdate(positionStart, itemCount, AdapterHelper.UpdateOp.ADD); } @Override public void onItemsChanged(RecyclerView recyclerView) { mLazySpanLookup.clear(); requestLayout(); } @Override public void onItemsMoved(RecyclerView recyclerView, int from, int to, int itemCount) { handleUpdate(from, to, AdapterHelper.UpdateOp.MOVE); } @Override public void onItemsUpdated(RecyclerView recyclerView, int positionStart, int itemCount, Object payload) { handleUpdate(positionStart, itemCount, AdapterHelper.UpdateOp.UPDATE); } /** * Checks whether it should invalidate span assignments in response to an adapter change. */ private void handleUpdate(int positionStart, int itemCountOrToPosition, int cmd) { int minPosition = mShouldReverseLayout ? getLastChildPosition() : getFirstChildPosition(); final int affectedRangeEnd;// exclusive final int affectedRangeStart;// inclusive if (cmd == AdapterHelper.UpdateOp.MOVE) { if (positionStart < itemCountOrToPosition) { affectedRangeEnd = itemCountOrToPosition + 1; affectedRangeStart = positionStart; } else { affectedRangeEnd = positionStart + 1; affectedRangeStart = itemCountOrToPosition; } } else { affectedRangeStart = positionStart; affectedRangeEnd = positionStart + itemCountOrToPosition; } mLazySpanLookup.invalidateAfter(affectedRangeStart); switch (cmd) { case AdapterHelper.UpdateOp.ADD: mLazySpanLookup.offsetForAddition(positionStart, itemCountOrToPosition); break; case AdapterHelper.UpdateOp.REMOVE: mLazySpanLookup.offsetForRemoval(positionStart, itemCountOrToPosition); break; case AdapterHelper.UpdateOp.MOVE: // TODO optimize mLazySpanLookup.offsetForRemoval(positionStart, 1); mLazySpanLookup.offsetForAddition(itemCountOrToPosition, 1); break; } if (affectedRangeEnd <= minPosition) { return; } int maxPosition = mShouldReverseLayout ? getFirstChildPosition() : getLastChildPosition(); if (affectedRangeStart <= maxPosition) { requestLayout(); } } private int fill(RecyclerView.Recycler recycler, LayoutState layoutState, RecyclerView.State state) { mRemainingSpans.set(0, mSpanCount, true); // The target position we are trying to reach. final int targetLine; // Line of the furthest row. if (mLayoutState.mInfinite) { if (layoutState.mLayoutDirection == LayoutState.LAYOUT_END) { targetLine = Integer.MAX_VALUE; } else { // LAYOUT_START targetLine = Integer.MIN_VALUE; } } else { if (layoutState.mLayoutDirection == LayoutState.LAYOUT_END) { targetLine = layoutState.mEndLine + layoutState.mAvailable; } else { // LAYOUT_START targetLine = layoutState.mStartLine - layoutState.mAvailable; } } updateAllRemainingSpans(layoutState.mLayoutDirection, targetLine); if (DEBUG) { Log.d(TAG, "FILLING targetLine: " + targetLine + "," + "remaining spans:" + mRemainingSpans + ", state: " + layoutState); } // the default coordinate to add new view. final int defaultNewViewLine = mShouldReverseLayout ? mPrimaryOrientation.getEndAfterPadding() : mPrimaryOrientation.getStartAfterPadding(); boolean added = false; while (layoutState.hasMore(state) && (mLayoutState.mInfinite || !mRemainingSpans.isEmpty())) { View view = layoutState.next(recycler); LayoutParams lp = ((LayoutParams) view.getLayoutParams()); final int position = lp.getViewLayoutPosition(); final int spanIndex = mLazySpanLookup.getSpan(position); Span currentSpan; final boolean assignSpan = spanIndex == LayoutParams.INVALID_SPAN_ID; if (assignSpan) { currentSpan = lp.mFullSpan ? mSpans[0] : getNextSpan(layoutState); mLazySpanLookup.setSpan(position, currentSpan); if (DEBUG) { Log.d(TAG, "assigned " + currentSpan.mIndex + " for " + position); } } else { if (DEBUG) { Log.d(TAG, "using " + spanIndex + " for pos " + position); } currentSpan = mSpans[spanIndex]; } // assign span before measuring so that item decorators can get updated span index lp.mSpan = currentSpan; if (layoutState.mLayoutDirection == LayoutState.LAYOUT_END) { addView(view); } else { addView(view, 0); } measureChildWithDecorationsAndMargin(view, lp, false); final int start; final int end; if (layoutState.mLayoutDirection == LayoutState.LAYOUT_END) { start = lp.mFullSpan ? getMaxEnd(defaultNewViewLine) : currentSpan.getEndLine(defaultNewViewLine); end = start + mPrimaryOrientation.getDecoratedMeasurement(view); if (assignSpan && lp.mFullSpan) { LazySpanLookup.FullSpanItem fullSpanItem; fullSpanItem = createFullSpanItemFromEnd(start); fullSpanItem.mGapDir = LayoutState.LAYOUT_START; fullSpanItem.mPosition = position; mLazySpanLookup.addFullSpanItem(fullSpanItem); } } else { end = lp.mFullSpan ? getMinStart(defaultNewViewLine) : currentSpan.getStartLine(defaultNewViewLine); start = end - mPrimaryOrientation.getDecoratedMeasurement(view); if (assignSpan && lp.mFullSpan) { LazySpanLookup.FullSpanItem fullSpanItem; fullSpanItem = createFullSpanItemFromStart(end); fullSpanItem.mGapDir = LayoutState.LAYOUT_END; fullSpanItem.mPosition = position; mLazySpanLookup.addFullSpanItem(fullSpanItem); } } // check if this item may create gaps in the future if (lp.mFullSpan && layoutState.mItemDirection == LayoutState.ITEM_DIRECTION_HEAD) { if (assignSpan) { mLaidOutInvalidFullSpan = true; } else { final boolean hasInvalidGap; if (layoutState.mLayoutDirection == LayoutState.LAYOUT_END) { hasInvalidGap = !areAllEndsEqual(); } else { // layoutState.mLayoutDirection == LAYOUT_START hasInvalidGap = !areAllStartsEqual(); } if (hasInvalidGap) { final LazySpanLookup.FullSpanItem fullSpanItem = mLazySpanLookup .getFullSpanItem(position); if (fullSpanItem != null) { fullSpanItem.mHasUnwantedGapAfter = true; } mLaidOutInvalidFullSpan = true; } } } attachViewToSpans(view, lp, layoutState); final int otherStart; final int otherEnd; if (isLayoutRTL() && mOrientation == VERTICAL) { otherEnd = lp.mFullSpan ? mSecondaryOrientation.getEndAfterPadding() : mSecondaryOrientation.getEndAfterPadding() - (mSpanCount - 1 - currentSpan.mIndex) * mSizePerSpan; otherStart = otherEnd - mSecondaryOrientation.getDecoratedMeasurement(view); } else { otherStart = lp.mFullSpan ? mSecondaryOrientation.getStartAfterPadding() : currentSpan.mIndex * mSizePerSpan + mSecondaryOrientation.getStartAfterPadding(); otherEnd = otherStart + mSecondaryOrientation.getDecoratedMeasurement(view); } if (mOrientation == VERTICAL) { layoutDecoratedWithMargins(view, otherStart, start, otherEnd, end); } else { layoutDecoratedWithMargins(view, start, otherStart, end, otherEnd); } if (lp.mFullSpan) { updateAllRemainingSpans(mLayoutState.mLayoutDirection, targetLine); } else { updateRemainingSpans(currentSpan, mLayoutState.mLayoutDirection, targetLine); } recycle(recycler, mLayoutState); if (mLayoutState.mStopInFocusable && view.isFocusable()) { if (lp.mFullSpan) { mRemainingSpans.clear(); } else { mRemainingSpans.set(currentSpan.mIndex, false); } } added = true; } if (!added) { recycle(recycler, mLayoutState); } final int diff; if (mLayoutState.mLayoutDirection == LayoutState.LAYOUT_START) { final int minStart = getMinStart(mPrimaryOrientation.getStartAfterPadding()); diff = mPrimaryOrientation.getStartAfterPadding() - minStart; } else { final int maxEnd = getMaxEnd(mPrimaryOrientation.getEndAfterPadding()); diff = maxEnd - mPrimaryOrientation.getEndAfterPadding(); } return diff > 0 ? Math.min(layoutState.mAvailable, diff) : 0; } private LazySpanLookup.FullSpanItem createFullSpanItemFromEnd(int newItemTop) { LazySpanLookup.FullSpanItem fsi = new LazySpanLookup.FullSpanItem(); fsi.mGapPerSpan = new int[mSpanCount]; for (int i = 0; i < mSpanCount; i++) { fsi.mGapPerSpan[i] = newItemTop - mSpans[i].getEndLine(newItemTop); } return fsi; } private LazySpanLookup.FullSpanItem createFullSpanItemFromStart(int newItemBottom) { LazySpanLookup.FullSpanItem fsi = new LazySpanLookup.FullSpanItem(); fsi.mGapPerSpan = new int[mSpanCount]; for (int i = 0; i < mSpanCount; i++) { fsi.mGapPerSpan[i] = mSpans[i].getStartLine(newItemBottom) - newItemBottom; } return fsi; } private void attachViewToSpans(View view, LayoutParams lp, LayoutState layoutState) { if (layoutState.mLayoutDirection == LayoutState.LAYOUT_END) { if (lp.mFullSpan) { appendViewToAllSpans(view); } else { lp.mSpan.appendToSpan(view); } } else { if (lp.mFullSpan) { prependViewToAllSpans(view); } else { lp.mSpan.prependToSpan(view); } } } private void recycle(RecyclerView.Recycler recycler, LayoutState layoutState) { if (!layoutState.mRecycle || layoutState.mInfinite) { return; } if (layoutState.mAvailable == 0) { // easy, recycle line is still valid if (layoutState.mLayoutDirection == LayoutState.LAYOUT_START) { recycleFromEnd(recycler, layoutState.mEndLine); } else { recycleFromStart(recycler, layoutState.mStartLine); } } else { // scrolling case, recycle line can be shifted by how much space we could cover // by adding new views if (layoutState.mLayoutDirection == LayoutState.LAYOUT_START) { // calculate recycle line int scrolled = layoutState.mStartLine - getMaxStart(layoutState.mStartLine); final int line; if (scrolled < 0) { line = layoutState.mEndLine; } else { line = layoutState.mEndLine - Math.min(scrolled, layoutState.mAvailable); } recycleFromEnd(recycler, line); } else { // calculate recycle line int scrolled = getMinEnd(layoutState.mEndLine) - layoutState.mEndLine; final int line; if (scrolled < 0) { line = layoutState.mStartLine; } else { line = layoutState.mStartLine + Math.min(scrolled, layoutState.mAvailable); } recycleFromStart(recycler, line); } } } private void appendViewToAllSpans(View view) { // traverse in reverse so that we end up assigning full span items to 0 for (int i = mSpanCount - 1; i >= 0; i--) { mSpans[i].appendToSpan(view); } } private void prependViewToAllSpans(View view) { // traverse in reverse so that we end up assigning full span items to 0 for (int i = mSpanCount - 1; i >= 0; i--) { mSpans[i].prependToSpan(view); } } private void layoutDecoratedWithMargins(View child, int left, int top, int right, int bottom) { LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (DEBUG) { Log.d(TAG, "layout decorated pos: " + lp.getViewLayoutPosition() + ", span:" + lp.getSpanIndex() + ", fullspan:" + lp.mFullSpan + ". l:" + left + ",t:" + top + ", r:" + right + ", b:" + bottom); } layoutDecorated(child, left + lp.leftMargin, top + lp.topMargin, right - lp.rightMargin , bottom - lp.bottomMargin); } private void updateAllRemainingSpans(int layoutDir, int targetLine) { for (int i = 0; i < mSpanCount; i++) { if (mSpans[i].mViews.isEmpty()) { continue; } updateRemainingSpans(mSpans[i], layoutDir, targetLine); } } private void updateRemainingSpans(Span span, int layoutDir, int targetLine) { final int deletedSize = span.getDeletedSize(); if (layoutDir == LayoutState.LAYOUT_START) { final int line = span.getStartLine(); if (line + deletedSize <= targetLine) { mRemainingSpans.set(span.mIndex, false); } } else { final int line = span.getEndLine(); if (line - deletedSize >= targetLine) { mRemainingSpans.set(span.mIndex, false); } } } private int getMaxStart(int def) { int maxStart = mSpans[0].getStartLine(def); for (int i = 1; i < mSpanCount; i++) { final int spanStart = mSpans[i].getStartLine(def); if (spanStart > maxStart) { maxStart = spanStart; } } return maxStart; } private int getMinStart(int def) { int minStart = mSpans[0].getStartLine(def); for (int i = 1; i < mSpanCount; i++) { final int spanStart = mSpans[i].getStartLine(def); if (spanStart < minStart) { minStart = spanStart; } } return minStart; } boolean areAllEndsEqual() { int end = mSpans[0].getEndLine(Span.INVALID_LINE); for (int i = 1; i < mSpanCount; i++) { if (mSpans[i].getEndLine(Span.INVALID_LINE) != end) { return false; } } return true; } boolean areAllStartsEqual() { int start = mSpans[0].getStartLine(Span.INVALID_LINE); for (int i = 1; i < mSpanCount; i++) { if (mSpans[i].getStartLine(Span.INVALID_LINE) != start) { return false; } } return true; } private int getMaxEnd(int def) { int maxEnd = mSpans[0].getEndLine(def); for (int i = 1; i < mSpanCount; i++) { final int spanEnd = mSpans[i].getEndLine(def); if (spanEnd > maxEnd) { maxEnd = spanEnd; } } return maxEnd; } private int getMinEnd(int def) { int minEnd = mSpans[0].getEndLine(def); for (int i = 1; i < mSpanCount; i++) { final int spanEnd = mSpans[i].getEndLine(def); if (spanEnd < minEnd) { minEnd = spanEnd; } } return minEnd; } private void recycleFromStart(RecyclerView.Recycler recycler, int line) { while (getChildCount() > 0) { View child = getChildAt(0); if (mPrimaryOrientation.getDecoratedEnd(child) <= line) { LayoutParams lp = (LayoutParams) child.getLayoutParams(); // Don't recycle the last View in a span not to lose span's start/end lines if (lp.mFullSpan) { for (int j = 0; j < mSpanCount; j++) { if (mSpans[j].mViews.size() == 1) { return; } } for (int j = 0; j < mSpanCount; j++) { mSpans[j].popStart(); } } else { if (lp.mSpan.mViews.size() == 1) { return; } lp.mSpan.popStart(); } removeAndRecycleView(child, recycler); } else { return;// done } } } private void recycleFromEnd(RecyclerView.Recycler recycler, int line) { final int childCount = getChildCount(); int i; for (i = childCount - 1; i >= 0; i--) { View child = getChildAt(i); if (mPrimaryOrientation.getDecoratedStart(child) >= line) { LayoutParams lp = (LayoutParams) child.getLayoutParams(); // Don't recycle the last View in a span not to lose span's start/end lines if (lp.mFullSpan) { for (int j = 0; j < mSpanCount; j++) { if (mSpans[j].mViews.size() == 1) { return; } } for (int j = 0; j < mSpanCount; j++) { mSpans[j].popEnd(); } } else { if (lp.mSpan.mViews.size() == 1) { return; } lp.mSpan.popEnd(); } removeAndRecycleView(child, recycler); } else { return;// done } } } /** * @return True if last span is the first one we want to fill */ private boolean preferLastSpan(int layoutDir) { if (mOrientation == HORIZONTAL) { return (layoutDir == LayoutState.LAYOUT_START) != mShouldReverseLayout; } return ((layoutDir == LayoutState.LAYOUT_START) == mShouldReverseLayout) == isLayoutRTL(); } /** * Finds the span for the next view. */ private Span getNextSpan(LayoutState layoutState) { final boolean preferLastSpan = preferLastSpan(layoutState.mLayoutDirection); final int startIndex, endIndex, diff; if (preferLastSpan) { startIndex = mSpanCount - 1; endIndex = -1; diff = -1; } else { startIndex = 0; endIndex = mSpanCount; diff = 1; } if (layoutState.mLayoutDirection == LayoutState.LAYOUT_END) { Span min = null; int minLine = Integer.MAX_VALUE; final int defaultLine = mPrimaryOrientation.getStartAfterPadding(); for (int i = startIndex; i != endIndex; i += diff) { final Span other = mSpans[i]; int otherLine = other.getEndLine(defaultLine); if (otherLine < minLine) { min = other; minLine = otherLine; } } return min; } else { Span max = null; int maxLine = Integer.MIN_VALUE; final int defaultLine = mPrimaryOrientation.getEndAfterPadding(); for (int i = startIndex; i != endIndex; i += diff) { final Span other = mSpans[i]; int otherLine = other.getStartLine(defaultLine); if (otherLine > maxLine) { max = other; maxLine = otherLine; } } return max; } } @Override public boolean canScrollVertically() { return mOrientation == VERTICAL; } @Override public boolean canScrollHorizontally() { return mOrientation == HORIZONTAL; } @Override public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) { return scrollBy(dx, recycler, state); } @Override public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) { return scrollBy(dy, recycler, state); } private int calculateScrollDirectionForPosition(int position) { if (getChildCount() == 0) { return mShouldReverseLayout ? LayoutState.LAYOUT_END : LayoutState.LAYOUT_START; } final int firstChildPos = getFirstChildPosition(); return position < firstChildPos != mShouldReverseLayout ? LayoutState.LAYOUT_START : LayoutState.LAYOUT_END; } @Override public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) { LinearSmoothScroller scroller = new LinearSmoothScroller(recyclerView.getContext()) { @Override public PointF computeScrollVectorForPosition(int targetPosition) { final int direction = calculateScrollDirectionForPosition(targetPosition); if (direction == 0) { return null; } if (mOrientation == HORIZONTAL) { return new PointF(direction, 0); } else { return new PointF(0, direction); } } }; scroller.setTargetPosition(position); startSmoothScroll(scroller); } @Override public void scrollToPosition(int position) { if (mPendingSavedState != null && mPendingSavedState.mAnchorPosition != position) { mPendingSavedState.invalidateAnchorPositionInfo(); } mPendingScrollPosition = position; mPendingScrollPositionOffset = INVALID_OFFSET; requestLayout(); } /** * Scroll to the specified adapter position with the given offset from layout start. * <p> * Note that scroll position change will not be reflected until the next layout call. * <p> * If you are just trying to make a position visible, use {@link #scrollToPosition(int)}. * * @param position Index (starting at 0) of the reference item. * @param offset The distance (in pixels) between the start edge of the item view and * start edge of the RecyclerView. * @see #setReverseLayout(boolean) * @see #scrollToPosition(int) */ public void scrollToPositionWithOffset(int position, int offset) { if (mPendingSavedState != null) { mPendingSavedState.invalidateAnchorPositionInfo(); } mPendingScrollPosition = position; mPendingScrollPositionOffset = offset; requestLayout(); } int scrollBy(int dt, RecyclerView.Recycler recycler, RecyclerView.State state) { final int referenceChildPosition; final int layoutDir; if (dt > 0) { // layout towards end layoutDir = LayoutState.LAYOUT_END; referenceChildPosition = getLastChildPosition(); } else { layoutDir = LayoutState.LAYOUT_START; referenceChildPosition = getFirstChildPosition(); } mLayoutState.mRecycle = true; updateLayoutState(referenceChildPosition, state); setLayoutStateDirection(layoutDir); mLayoutState.mCurrentPosition = referenceChildPosition + mLayoutState.mItemDirection; final int absDt = Math.abs(dt); mLayoutState.mAvailable = absDt; int consumed = fill(recycler, mLayoutState, state); final int totalScroll; if (absDt < consumed) { totalScroll = dt; } else if (dt < 0) { totalScroll = -consumed; } else { // dt > 0 totalScroll = consumed; } if (DEBUG) { Log.d(TAG, "asked " + dt + " scrolled" + totalScroll); } mPrimaryOrientation.offsetChildren(-totalScroll); // always reset this if we scroll for a proper save instance state mLastLayoutFromEnd = mShouldReverseLayout; return totalScroll; } private int getLastChildPosition() { final int childCount = getChildCount(); return childCount == 0 ? 0 : getPosition(getChildAt(childCount - 1)); } private int getFirstChildPosition() { final int childCount = getChildCount(); return childCount == 0 ? 0 : getPosition(getChildAt(0)); } /** * Finds the first View that can be used as an anchor View. * * @return Position of the View or 0 if it cannot find any such View. */ private int findFirstReferenceChildPosition(int itemCount) { final int limit = getChildCount(); for (int i = 0; i < limit; i++) { final View view = getChildAt(i); final int position = getPosition(view); if (position >= 0 && position < itemCount) { return position; } } return 0; } /** * Finds the last View that can be used as an anchor View. * * @return Position of the View or 0 if it cannot find any such View. */ private int findLastReferenceChildPosition(int itemCount) { for (int i = getChildCount() - 1; i >= 0; i--) { final View view = getChildAt(i); final int position = getPosition(view); if (position >= 0 && position < itemCount) { return position; } } return 0; } @SuppressWarnings("deprecation") @Override public RecyclerView.LayoutParams generateDefaultLayoutParams() { if (mOrientation == HORIZONTAL) { return new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.FILL_PARENT); } else { return new LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } } @Override public RecyclerView.LayoutParams generateLayoutParams(Context c, AttributeSet attrs) { return new LayoutParams(c, attrs); } @Override public RecyclerView.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) { if (lp instanceof ViewGroup.MarginLayoutParams) { return new LayoutParams((ViewGroup.MarginLayoutParams) lp); } else { return new LayoutParams(lp); } } @Override public boolean checkLayoutParams(RecyclerView.LayoutParams lp) { return lp instanceof LayoutParams; } public int getOrientation() { return mOrientation; } @Nullable @Override public View onFocusSearchFailed(View focused, int direction, RecyclerView.Recycler recycler, RecyclerView.State state) { if (getChildCount() == 0) { return null; } final View directChild = findContainingItemView(focused); if (directChild == null) { return null; } resolveShouldLayoutReverse(); final int layoutDir = convertFocusDirectionToLayoutDirection(direction); if (layoutDir == LayoutState.INVALID_LAYOUT) { return null; } LayoutParams prevFocusLayoutParams = (LayoutParams) directChild.getLayoutParams(); boolean prevFocusFullSpan = prevFocusLayoutParams.mFullSpan; final Span prevFocusSpan = prevFocusLayoutParams.mSpan; final int referenceChildPosition; if (layoutDir == LayoutState.LAYOUT_END) { // layout towards end referenceChildPosition = getLastChildPosition(); } else { referenceChildPosition = getFirstChildPosition(); } updateLayoutState(referenceChildPosition, state); setLayoutStateDirection(layoutDir); mLayoutState.mCurrentPosition = referenceChildPosition + mLayoutState.mItemDirection; mLayoutState.mAvailable = (int) (MAX_SCROLL_FACTOR * mPrimaryOrientation.getTotalSpace()); mLayoutState.mStopInFocusable = true; mLayoutState.mRecycle = false; fill(recycler, mLayoutState, state); mLastLayoutFromEnd = mShouldReverseLayout; if (!prevFocusFullSpan) { View view = prevFocusSpan.getFocusableViewAfter(referenceChildPosition, layoutDir); if (view != null && view != directChild) { return view; } } // either could not find from the desired span or prev view is full span. // traverse all spans if (preferLastSpan(layoutDir)) { for (int i = mSpanCount - 1; i >= 0; i --) { View view = mSpans[i].getFocusableViewAfter(referenceChildPosition, layoutDir); if (view != null && view != directChild) { return view; } } } else { for (int i = 0; i < mSpanCount; i ++) { View view = mSpans[i].getFocusableViewAfter(referenceChildPosition, layoutDir); if (view != null && view != directChild) { return view; } } } return null; } /** * Converts a focusDirection to orientation. * * @param focusDirection One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, * {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT}, * {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD} * or 0 for not applicable * @return {@link LayoutState#LAYOUT_START} or {@link LayoutState#LAYOUT_END} if focus direction * is applicable to current state, {@link LayoutState#INVALID_LAYOUT} otherwise. */ private int convertFocusDirectionToLayoutDirection(int focusDirection) { switch (focusDirection) { case View.FOCUS_BACKWARD: return LayoutState.LAYOUT_START; case View.FOCUS_FORWARD: return LayoutState.LAYOUT_END; case View.FOCUS_UP: return mOrientation == VERTICAL ? LayoutState.LAYOUT_START : LayoutState.INVALID_LAYOUT; case View.FOCUS_DOWN: return mOrientation == VERTICAL ? LayoutState.LAYOUT_END : LayoutState.INVALID_LAYOUT; case View.FOCUS_LEFT: return mOrientation == HORIZONTAL ? LayoutState.LAYOUT_START : LayoutState.INVALID_LAYOUT; case View.FOCUS_RIGHT: return mOrientation == HORIZONTAL ? LayoutState.LAYOUT_END : LayoutState.INVALID_LAYOUT; default: if (DEBUG) { Log.d(TAG, "Unknown focus request:" + focusDirection); } return LayoutState.INVALID_LAYOUT; } } /** * LayoutParams used by StaggeredGridLayoutManager. * <p> * Note that if the orientation is {@link #VERTICAL}, the width parameter is ignored and if the * orientation is {@link #HORIZONTAL} the height parameter is ignored because child view is * expected to fill all of the space given to it. */ public static class LayoutParams extends RecyclerView.LayoutParams { /** * Span Id for Views that are not laid out yet. */ public static final int INVALID_SPAN_ID = -1; // Package scope to be able to access from tests. Span mSpan; boolean mFullSpan; public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); } public LayoutParams(int width, int height) { super(width, height); } public LayoutParams(ViewGroup.MarginLayoutParams source) { super(source); } public LayoutParams(ViewGroup.LayoutParams source) { super(source); } public LayoutParams(RecyclerView.LayoutParams source) { super(source); } /** * When set to true, the item will layout using all span area. That means, if orientation * is vertical, the view will have full width; if orientation is horizontal, the view will * have full height. * * @param fullSpan True if this item should traverse all spans. * @see #isFullSpan() */ public void setFullSpan(boolean fullSpan) { mFullSpan = fullSpan; } /** * Returns whether this View occupies all available spans or just one. * * @return True if the View occupies all spans or false otherwise. * @see #setFullSpan(boolean) */ public boolean isFullSpan() { return mFullSpan; } /** * Returns the Span index to which this View is assigned. * * @return The Span index of the View. If View is not yet assigned to any span, returns * {@link #INVALID_SPAN_ID}. */ public final int getSpanIndex() { if (mSpan == null) { return INVALID_SPAN_ID; } return mSpan.mIndex; } } // Package scoped to access from tests. class Span { static final int INVALID_LINE = Integer.MIN_VALUE; private ArrayList<View> mViews = new ArrayList<>(); int mCachedStart = INVALID_LINE; int mCachedEnd = INVALID_LINE; int mDeletedSize = 0; final int mIndex; private Span(int index) { mIndex = index; } int getStartLine(int def) { if (mCachedStart != INVALID_LINE) { return mCachedStart; } if (mViews.size() == 0) { return def; } calculateCachedStart(); return mCachedStart; } void calculateCachedStart() { final View startView = mViews.get(0); final LayoutParams lp = getLayoutParams(startView); mCachedStart = mPrimaryOrientation.getDecoratedStart(startView); if (lp.mFullSpan) { LazySpanLookup.FullSpanItem fsi = mLazySpanLookup .getFullSpanItem(lp.getViewLayoutPosition()); if (fsi != null && fsi.mGapDir == LayoutState.LAYOUT_START) { mCachedStart -= fsi.getGapForSpan(mIndex); } } } // Use this one when default value does not make sense and not having a value means a bug. int getStartLine() { if (mCachedStart != INVALID_LINE) { return mCachedStart; } calculateCachedStart(); return mCachedStart; } int getEndLine(int def) { if (mCachedEnd != INVALID_LINE) { return mCachedEnd; } final int size = mViews.size(); if (size == 0) { return def; } calculateCachedEnd(); return mCachedEnd; } void calculateCachedEnd() { final View endView = mViews.get(mViews.size() - 1); final LayoutParams lp = getLayoutParams(endView); mCachedEnd = mPrimaryOrientation.getDecoratedEnd(endView); if (lp.mFullSpan) { LazySpanLookup.FullSpanItem fsi = mLazySpanLookup .getFullSpanItem(lp.getViewLayoutPosition()); if (fsi != null && fsi.mGapDir == LayoutState.LAYOUT_END) { mCachedEnd += fsi.getGapForSpan(mIndex); } } } // Use this one when default value does not make sense and not having a value means a bug. int getEndLine() { if (mCachedEnd != INVALID_LINE) { return mCachedEnd; } calculateCachedEnd(); return mCachedEnd; } void prependToSpan(View view) { LayoutParams lp = getLayoutParams(view); lp.mSpan = this; mViews.add(0, view); mCachedStart = INVALID_LINE; if (mViews.size() == 1) { mCachedEnd = INVALID_LINE; } if (lp.isItemRemoved() || lp.isItemChanged()) { mDeletedSize += mPrimaryOrientation.getDecoratedMeasurement(view); } } void appendToSpan(View view) { LayoutParams lp = getLayoutParams(view); lp.mSpan = this; mViews.add(view); mCachedEnd = INVALID_LINE; if (mViews.size() == 1) { mCachedStart = INVALID_LINE; } if (lp.isItemRemoved() || lp.isItemChanged()) { mDeletedSize += mPrimaryOrientation.getDecoratedMeasurement(view); } } // Useful method to preserve positions on a re-layout. void cacheReferenceLineAndClear(boolean reverseLayout, int offset) { int reference; if (reverseLayout) { reference = getEndLine(INVALID_LINE); } else { reference = getStartLine(INVALID_LINE); } clear(); if (reference == INVALID_LINE) { return; } if ((reverseLayout && reference < mPrimaryOrientation.getEndAfterPadding()) || (!reverseLayout && reference > mPrimaryOrientation.getStartAfterPadding())) { return; } if (offset != INVALID_OFFSET) { reference += offset; } mCachedStart = mCachedEnd = reference; } void clear() { mViews.clear(); invalidateCache(); mDeletedSize = 0; } void invalidateCache() { mCachedStart = INVALID_LINE; mCachedEnd = INVALID_LINE; } void setLine(int line) { mCachedEnd = mCachedStart = line; } void popEnd() { final int size = mViews.size(); View end = mViews.remove(size - 1); final LayoutParams lp = getLayoutParams(end); lp.mSpan = null; if (lp.isItemRemoved() || lp.isItemChanged()) { mDeletedSize -= mPrimaryOrientation.getDecoratedMeasurement(end); } if (size == 1) { mCachedStart = INVALID_LINE; } mCachedEnd = INVALID_LINE; } void popStart() { View start = mViews.remove(0); final LayoutParams lp = getLayoutParams(start); lp.mSpan = null; if (mViews.size() == 0) { mCachedEnd = INVALID_LINE; } if (lp.isItemRemoved() || lp.isItemChanged()) { mDeletedSize -= mPrimaryOrientation.getDecoratedMeasurement(start); } mCachedStart = INVALID_LINE; } public int getDeletedSize() { return mDeletedSize; } LayoutParams getLayoutParams(View view) { return (LayoutParams) view.getLayoutParams(); } void onOffset(int dt) { if (mCachedStart != INVALID_LINE) { mCachedStart += dt; } if (mCachedEnd != INVALID_LINE) { mCachedEnd += dt; } } public int findFirstVisibleItemPosition() { return mReverseLayout ? findOneVisibleChild(mViews.size() - 1, -1, false) : findOneVisibleChild(0, mViews.size(), false); } public int findFirstCompletelyVisibleItemPosition() { return mReverseLayout ? findOneVisibleChild(mViews.size() - 1, -1, true) : findOneVisibleChild(0, mViews.size(), true); } public int findLastVisibleItemPosition() { return mReverseLayout ? findOneVisibleChild(0, mViews.size(), false) : findOneVisibleChild(mViews.size() - 1, -1, false); } public int findLastCompletelyVisibleItemPosition() { return mReverseLayout ? findOneVisibleChild(0, mViews.size(), true) : findOneVisibleChild(mViews.size() - 1, -1, true); } int findOneVisibleChild(int fromIndex, int toIndex, boolean completelyVisible) { final int start = mPrimaryOrientation.getStartAfterPadding(); final int end = mPrimaryOrientation.getEndAfterPadding(); final int next = toIndex > fromIndex ? 1 : -1; for (int i = fromIndex; i != toIndex; i += next) { final View child = mViews.get(i); final int childStart = mPrimaryOrientation.getDecoratedStart(child); final int childEnd = mPrimaryOrientation.getDecoratedEnd(child); if (childStart < end && childEnd > start) { if (completelyVisible) { if (childStart >= start && childEnd <= end) { return getPosition(child); } } else { return getPosition(child); } } } return NO_POSITION; } /** * Depending on the layout direction, returns the View that is after the given position. */ public View getFocusableViewAfter(int referenceChildPosition, int layoutDir) { View candidate = null; if (layoutDir == LayoutState.LAYOUT_START) { final int limit = mViews.size(); for (int i = 0; i < limit; i++) { final View view = mViews.get(i); if (view.isFocusable() && (getPosition(view) > referenceChildPosition == mReverseLayout) ) { candidate = view; } else { break; } } } else { for (int i = mViews.size() - 1; i >= 0; i--) { final View view = mViews.get(i); if (view.isFocusable() && (getPosition(view) > referenceChildPosition == !mReverseLayout)) { candidate = view; } else { break; } } } return candidate; } } /** * An array of mappings from adapter position to span. * This only grows when a write happens and it grows up to the size of the adapter. */ static class LazySpanLookup { private static final int MIN_SIZE = 10; int[] mData; List<FullSpanItem> mFullSpanItems; /** * Invalidates everything after this position, including full span information */ int forceInvalidateAfter(int position) { if (mFullSpanItems != null) { for (int i = mFullSpanItems.size() - 1; i >= 0; i--) { FullSpanItem fsi = mFullSpanItems.get(i); if (fsi.mPosition >= position) { mFullSpanItems.remove(i); } } } return invalidateAfter(position); } /** * returns end position for invalidation. */ int invalidateAfter(int position) { if (mData == null) { return RecyclerView.NO_POSITION; } if (position >= mData.length) { return RecyclerView.NO_POSITION; } int endPosition = invalidateFullSpansAfter(position); if (endPosition == RecyclerView.NO_POSITION) { Arrays.fill(mData, position, mData.length, LayoutParams.INVALID_SPAN_ID); return mData.length; } else { // just invalidate items in between Arrays.fill(mData, position, endPosition + 1, LayoutParams.INVALID_SPAN_ID); return endPosition + 1; } } int getSpan(int position) { if (mData == null || position >= mData.length) { return LayoutParams.INVALID_SPAN_ID; } else { return mData[position]; } } void setSpan(int position, Span span) { ensureSize(position); mData[position] = span.mIndex; } int sizeForPosition(int position) { int len = mData.length; while (len <= position) { len *= 2; } return len; } void ensureSize(int position) { if (mData == null) { mData = new int[Math.max(position, MIN_SIZE) + 1]; Arrays.fill(mData, LayoutParams.INVALID_SPAN_ID); } else if (position >= mData.length) { int[] old = mData; mData = new int[sizeForPosition(position)]; System.arraycopy(old, 0, mData, 0, old.length); Arrays.fill(mData, old.length, mData.length, LayoutParams.INVALID_SPAN_ID); } } void clear() { if (mData != null) { Arrays.fill(mData, LayoutParams.INVALID_SPAN_ID); } mFullSpanItems = null; } void offsetForRemoval(int positionStart, int itemCount) { if (mData == null || positionStart >= mData.length) { return; } ensureSize(positionStart + itemCount); System.arraycopy(mData, positionStart + itemCount, mData, positionStart, mData.length - positionStart - itemCount); Arrays.fill(mData, mData.length - itemCount, mData.length, LayoutParams.INVALID_SPAN_ID); offsetFullSpansForRemoval(positionStart, itemCount); } private void offsetFullSpansForRemoval(int positionStart, int itemCount) { if (mFullSpanItems == null) { return; } final int end = positionStart + itemCount; for (int i = mFullSpanItems.size() - 1; i >= 0; i--) { FullSpanItem fsi = mFullSpanItems.get(i); if (fsi.mPosition < positionStart) { continue; } if (fsi.mPosition < end) { mFullSpanItems.remove(i); } else { fsi.mPosition -= itemCount; } } } void offsetForAddition(int positionStart, int itemCount) { if (mData == null || positionStart >= mData.length) { return; } ensureSize(positionStart + itemCount); System.arraycopy(mData, positionStart, mData, positionStart + itemCount, mData.length - positionStart - itemCount); Arrays.fill(mData, positionStart, positionStart + itemCount, LayoutParams.INVALID_SPAN_ID); offsetFullSpansForAddition(positionStart, itemCount); } private void offsetFullSpansForAddition(int positionStart, int itemCount) { if (mFullSpanItems == null) { return; } for (int i = mFullSpanItems.size() - 1; i >= 0; i--) { FullSpanItem fsi = mFullSpanItems.get(i); if (fsi.mPosition < positionStart) { continue; } fsi.mPosition += itemCount; } } /** * Returns when invalidation should end. e.g. hitting a full span position. * Returned position SHOULD BE invalidated. */ private int invalidateFullSpansAfter(int position) { if (mFullSpanItems == null) { return RecyclerView.NO_POSITION; } final FullSpanItem item = getFullSpanItem(position); // if there is an fsi at this position, get rid of it. if (item != null) { mFullSpanItems.remove(item); } int nextFsiIndex = -1; final int count = mFullSpanItems.size(); for (int i = 0; i < count; i++) { FullSpanItem fsi = mFullSpanItems.get(i); if (fsi.mPosition >= position) { nextFsiIndex = i; break; } } if (nextFsiIndex != -1) { FullSpanItem fsi = mFullSpanItems.get(nextFsiIndex); mFullSpanItems.remove(nextFsiIndex); return fsi.mPosition; } return RecyclerView.NO_POSITION; } public void addFullSpanItem(FullSpanItem fullSpanItem) { if (mFullSpanItems == null) { mFullSpanItems = new ArrayList<>(); } final int size = mFullSpanItems.size(); for (int i = 0; i < size; i++) { FullSpanItem other = mFullSpanItems.get(i); if (other.mPosition == fullSpanItem.mPosition) { if (DEBUG) { throw new IllegalStateException("two fsis for same position"); } else { mFullSpanItems.remove(i); } } if (other.mPosition >= fullSpanItem.mPosition) { mFullSpanItems.add(i, fullSpanItem); return; } } // if it is not added to a position. mFullSpanItems.add(fullSpanItem); } public FullSpanItem getFullSpanItem(int position) { if (mFullSpanItems == null) { return null; } for (int i = mFullSpanItems.size() - 1; i >= 0; i--) { final FullSpanItem fsi = mFullSpanItems.get(i); if (fsi.mPosition == position) { return fsi; } } return null; } /** * @param minPos inclusive * @param maxPos exclusive * @param gapDir if not 0, returns FSIs on in that direction * @param hasUnwantedGapAfter If true, when full span item has unwanted gaps, it will be * returned even if its gap direction does not match. */ public FullSpanItem getFirstFullSpanItemInRange(int minPos, int maxPos, int gapDir, boolean hasUnwantedGapAfter) { if (mFullSpanItems == null) { return null; } final int limit = mFullSpanItems.size(); for (int i = 0; i < limit; i++) { FullSpanItem fsi = mFullSpanItems.get(i); if (fsi.mPosition >= maxPos) { return null; } if (fsi.mPosition >= minPos && (gapDir == 0 || fsi.mGapDir == gapDir || (hasUnwantedGapAfter && fsi.mHasUnwantedGapAfter))) { return fsi; } } return null; } /** * We keep information about full span items because they may create gaps in the UI. */ static class FullSpanItem implements Parcelable { int mPosition; int mGapDir; int[] mGapPerSpan; // A full span may be laid out in primary direction but may have gaps due to // invalidation of views after it. This is recorded during a reverse scroll and if // view is still on the screen after scroll stops, we have to recalculate layout boolean mHasUnwantedGapAfter; public FullSpanItem(Parcel in) { mPosition = in.readInt(); mGapDir = in.readInt(); mHasUnwantedGapAfter = in.readInt() == 1; int spanCount = in.readInt(); if (spanCount > 0) { mGapPerSpan = new int[spanCount]; in.readIntArray(mGapPerSpan); } } public FullSpanItem() { } int getGapForSpan(int spanIndex) { return mGapPerSpan == null ? 0 : mGapPerSpan[spanIndex]; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(mPosition); dest.writeInt(mGapDir); dest.writeInt(mHasUnwantedGapAfter ? 1 : 0); if (mGapPerSpan != null && mGapPerSpan.length > 0) { dest.writeInt(mGapPerSpan.length); dest.writeIntArray(mGapPerSpan); } else { dest.writeInt(0); } } @Override public String toString() { return "FullSpanItem{" + "mPosition=" + mPosition + ", mGapDir=" + mGapDir + ", mHasUnwantedGapAfter=" + mHasUnwantedGapAfter + ", mGapPerSpan=" + Arrays.toString(mGapPerSpan) + '}'; } public static final Parcelable.Creator<FullSpanItem> CREATOR = new Parcelable.Creator<FullSpanItem>() { @Override public FullSpanItem createFromParcel(Parcel in) { return new FullSpanItem(in); } @Override public FullSpanItem[] newArray(int size) { return new FullSpanItem[size]; } }; } } /** * @hide */ public static class SavedState implements Parcelable { int mAnchorPosition; int mVisibleAnchorPosition; // Replacement for span info when spans are invalidated int mSpanOffsetsSize; int[] mSpanOffsets; int mSpanLookupSize; int[] mSpanLookup; List<LazySpanLookup.FullSpanItem> mFullSpanItems; boolean mReverseLayout; boolean mAnchorLayoutFromEnd; boolean mLastLayoutRTL; public SavedState() { } SavedState(Parcel in) { mAnchorPosition = in.readInt(); mVisibleAnchorPosition = in.readInt(); mSpanOffsetsSize = in.readInt(); if (mSpanOffsetsSize > 0) { mSpanOffsets = new int[mSpanOffsetsSize]; in.readIntArray(mSpanOffsets); } mSpanLookupSize = in.readInt(); if (mSpanLookupSize > 0) { mSpanLookup = new int[mSpanLookupSize]; in.readIntArray(mSpanLookup); } mReverseLayout = in.readInt() == 1; mAnchorLayoutFromEnd = in.readInt() == 1; mLastLayoutRTL = in.readInt() == 1; //noinspection unchecked mFullSpanItems = in.readArrayList( LazySpanLookup.FullSpanItem.class.getClassLoader()); } public SavedState(SavedState other) { mSpanOffsetsSize = other.mSpanOffsetsSize; mAnchorPosition = other.mAnchorPosition; mVisibleAnchorPosition = other.mVisibleAnchorPosition; mSpanOffsets = other.mSpanOffsets; mSpanLookupSize = other.mSpanLookupSize; mSpanLookup = other.mSpanLookup; mReverseLayout = other.mReverseLayout; mAnchorLayoutFromEnd = other.mAnchorLayoutFromEnd; mLastLayoutRTL = other.mLastLayoutRTL; mFullSpanItems = other.mFullSpanItems; } void invalidateSpanInfo() { mSpanOffsets = null; mSpanOffsetsSize = 0; mSpanLookupSize = 0; mSpanLookup = null; mFullSpanItems = null; } void invalidateAnchorPositionInfo() { mSpanOffsets = null; mSpanOffsetsSize = 0; mAnchorPosition = NO_POSITION; mVisibleAnchorPosition = NO_POSITION; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(mAnchorPosition); dest.writeInt(mVisibleAnchorPosition); dest.writeInt(mSpanOffsetsSize); if (mSpanOffsetsSize > 0) { dest.writeIntArray(mSpanOffsets); } dest.writeInt(mSpanLookupSize); if (mSpanLookupSize > 0) { dest.writeIntArray(mSpanLookup); } dest.writeInt(mReverseLayout ? 1 : 0); dest.writeInt(mAnchorLayoutFromEnd ? 1 : 0); dest.writeInt(mLastLayoutRTL ? 1 : 0); dest.writeList(mFullSpanItems); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } /** * Data class to hold the information about an anchor position which is used in onLayout call. */ private class AnchorInfo { int mPosition; int mOffset; boolean mLayoutFromEnd; boolean mInvalidateOffsets; void reset() { mPosition = NO_POSITION; mOffset = INVALID_OFFSET; mLayoutFromEnd = false; mInvalidateOffsets = false; } void assignCoordinateFromPadding() { mOffset = mLayoutFromEnd ? mPrimaryOrientation.getEndAfterPadding() : mPrimaryOrientation.getStartAfterPadding(); } void assignCoordinateFromPadding(int addedDistance) { if (mLayoutFromEnd) { mOffset = mPrimaryOrientation.getEndAfterPadding() - addedDistance; } else { mOffset = mPrimaryOrientation.getStartAfterPadding() + addedDistance; } } } }
amirlotfi/Nikagram
app/src/main/java/ir/nikagram/messenger/support/widget/StaggeredGridLayoutManager.java
Java
gpl-2.0
117,717
<?php /* * * Ampoliros Application Server * * http://www.ampoliros.com * * * * Copyright (C) 2000-2004 Solarix * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ // $Id: AllAmpolirosTests.php,v 1.4 2004-07-08 15:04:27 alex Exp $ /** * Ampoliros test case. * How to run the tests: * carthag carthag.dev.unit.textui.TestRunner AllAmpolirosTests * @package com.solarix.ampoliros.tests * @author Alex Pagnoni <alex.pagnoni@solarix.it> * @copyright Copyright 2000-2004 Solarix Srl * @since 4.0 */ package('com.solarix.ampoliros.tests'); import('carthag.dev.unit.framework.TestSuite'); import('com.solarix.ampoliros.tests.core.AllAmpolirosCoreTests'); import('com.solarix.ampoliros.tests.datatransfer.AllAmpolirosDatatransferTests'); /** * @package com.solarix.ampoliros.tests * @author Alex Pagnoni <alex.pagnoni@solarix.it> * @copyright Copyright 2000-2004 Solarix Srl * @since 4.0 */ class AllAmpolirosTests extends Object { public static function suite() { require('ampoliros.php'); $suite= new TestSuite('Ampoliros'); $suite -> addTest(AllAmpolirosCoreTests :: suite()); $suite -> addTest(AllAmpolirosDatatransferTests :: suite()); return $suite; } } ?>
alexpagnoni/ampoliros
var/classes/com/solarix/ampoliros/tests/AllAmpolirosTests.php
PHP
gpl-2.0
1,961
# vim:fileencoding=utf-8:noet try: import pygit2 as git class Repository(object): __slots__ = ('directory') def __init__(self, directory): self.directory = directory def _repo(self): return git.Repository(self.directory) def status(self, path=None): '''Return status of repository or file. Without file argument: returns status of the repository: :First column: working directory status (D: dirty / space) :Second column: index status (I: index dirty / space) :Third column: presense of untracked files (U: untracked files / space) :None: repository clean With file argument: returns status of this file. Output is equivalent to the first two columns of "git status --porcelain" (except for merge statuses as they are not supported by libgit2). ''' if path: try: status = self._repo().status_file(path) except (KeyError, ValueError): return None if status == git.GIT_STATUS_CURRENT: return None else: if status & git.GIT_STATUS_WT_NEW: return '??' if status & git.GIT_STATUS_IGNORED: return '!!' if status & git.GIT_STATUS_INDEX_NEW: index_status = 'A' elif status & git.GIT_STATUS_INDEX_DELETED: index_status = 'D' elif status & git.GIT_STATUS_INDEX_MODIFIED: index_status = 'M' else: index_status = ' ' if status & git.GIT_STATUS_WT_DELETED: wt_status = 'D' elif status & git.GIT_STATUS_WT_MODIFIED: wt_status = 'M' else: wt_status = ' ' return index_status + wt_status else: wt_column = ' ' index_column = ' ' untracked_column = ' ' for status in self._repo().status().values(): if status & git.GIT_STATUS_WT_NEW: untracked_column = 'U' continue if status & (git.GIT_STATUS_WT_DELETED | git.GIT_STATUS_WT_MODIFIED): wt_column = 'D' if status & (git.GIT_STATUS_INDEX_NEW | git.GIT_STATUS_INDEX_MODIFIED | git.GIT_STATUS_INDEX_DELETED): index_column = 'I' r = wt_column + index_column + untracked_column return r if r != ' ' else None def branch(self): try: ref = self._repo().lookup_reference('HEAD') except KeyError: return None try: target = ref.target except ValueError: return '[DETACHED HEAD]' if target.startswith('refs/heads/'): return target[11:] else: return '[DETACHED HEAD]' except ImportError: from subprocess import Popen, PIPE def readlines(cmd, cwd): p = Popen(cmd, shell=False, stdout=PIPE, stderr=PIPE, cwd=cwd) p.stderr.close() with p.stdout: for line in p.stdout: yield line[:-1].decode('utf-8') class Repository(object): __slots__ = ('directory',) def __init__(self, directory): self.directory = directory def _gitcmd(self, *args): return readlines(('git',) + args, self.directory) def status(self, path=None): if path: try: return next(self._gitcmd('status', '--porcelain', '--ignored', '--', path))[:2] except StopIteration: return None else: wt_column = ' ' index_column = ' ' untracked_column = ' ' for line in self._gitcmd('status', '--porcelain'): if line[0] == '?': untracked_column = 'U' continue elif line[0] == '!': continue if line[0] != ' ': index_column = 'I' if line[1] != ' ': wt_column = 'D' r = wt_column + index_column + untracked_column return r if r != ' ' else None def branch(self): for line in self._gitcmd('branch', '-l'): if line[0] == '*': return line[2:] return None
DaneelOliwan/dotfiles-vim
.vim/bundle/powerline/powerline/lib/vcs/git.py
Python
gpl-2.0
3,605
<?php /** * Mkdir class * * Class to rename directory/file & manage errors in doing so. * * PHP version 3 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the * Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * @category Chisimba * @package files * @author David Wafula * @copyright 2010, University of the Witwatersrand & AVOIR Project * @license http://www.gnu.org/licenses/gpl-2.0.txt The GNU General Public License * @link http://avoir.uwc.ac.za,http://www.chisimba.com * @see References to other sections (if any)... */ class rename extends object { /** * * @var string $oldFilePath The old file including its path, * or the folder if rename a folder. * */ var $oldFilePath; /** * * @var string $newFilePath The new file including its path, * or the folder if rename a folder. * */ var $newFilePath; /** * * @var boolean $err TRUE|FALSE; TRUE if error, else false * */ var $err; /** * * @var string $errMst The error message * */ var $errMsg; /** * * @var object $objLanguage String to hold the language object * */ var $objLanguage; /** * * Standard init method to set the default values for * the properties. * */ function init() { $this->oldFilePath = NULL; $this->newFilePath = NULL; $this->err = NULL; $this->errMsg = NULL; // Create an instance of the language object $this->objLanguage = $this->getObject('language', 'language'); } /** * * Renames a file/folder. Needs oldFilePath and newFilePath to be set * to a valid path before hand * * @access Public * */ function rename() { if ($this->oldFilePath != NULL && $this->newFilePath != NULL) { rename($this->oldFilePath,$this->newFilePath); //If the file path is null } else { $this->err = TRUE; $this->errMsg = $this->objLanguage->languageText('mod_files_err_nofilepath') . ": Old - " . $this->oldFilePath.", New - " . $this->newFilePath; return FALSE; } } //function } // end of class ?>
chisimba/chisimba
app/core_modules/files/classes/rename_class_inc.php
PHP
gpl-2.0
2,996
var searchData= [ ['vectororient',['vectorOrient',['../group___t_xC3_xA1rol_xC3_xB3k.html#gab13a5c3bc64237cc95301c3359a757c8',1,'RobotStateHistory']]] ];
muszkab/Alkalmazasfejlesztes-hazi
RobotDiagnosticApp/docs/html/search/variables_b.js
JavaScript
gpl-2.0
156
/* $Revision: 77449 $ */ /** @file * VBoxGuestLibR0 - Physical memory heap. */ /* * Copyright (C) 2006-2007 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. * * The contents of this file may alternatively be used under the terms * of the Common Development and Distribution License Version 1.0 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the * VirtualBox OSE distribution, in which case the provisions of the * CDDL are applicable instead of those of the GPL. * * You may elect to license modified versions of this file under the * terms and conditions of either the GPL or the CDDL or both. */ #include "VBGLInternal.h" /** * Checks whether the host supports physical page lists or not. * * @returns true if it does, false if it doesn't. */ DECLR0VBGL(bool) VbglR0CanUsePhysPageList(void) { int rc = vbglR0Enter(); return RT_SUCCESS(rc) && VBGLR0_CAN_USE_PHYS_PAGE_LIST(/*a_fLocked =*/ false); }
VirtualMonitor/VirtualMonitor
src/VBox/Additions/common/VBoxGuestLib/VbglR0CanUsePhysPageList.cpp
C++
gpl-2.0
1,404
<?php /* * This file is part of PHPExifTool. * * (c) 2012 Romain Neutron <imprec@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\DICOM; use PHPExiftool\Driver\AbstractTag; class GridPitch extends AbstractTag { protected $Id = '0018,7044'; protected $Name = 'GridPitch'; protected $FullName = 'DICOM::Main'; protected $GroupName = 'DICOM'; protected $g0 = 'DICOM'; protected $g1 = 'DICOM'; protected $g2 = 'Image'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Grid Pitch'; }
Droces/casabio
vendor/phpexiftool/phpexiftool/lib/PHPExiftool/Driver/Tag/DICOM/GridPitch.php
PHP
gpl-2.0
695
from random import randint, shuffle, choice from time import clock from _utils import InvalidTableException, copy_table def solve(table): table = _check_table(table) if _is_done(table): return table else: coordinates = _get_minimum_array(table) trials = table[coordinates[0]][coordinates[1]]["possibilities"][:] shuffle(trials) for elem in trials: try: ctable = copy_table(table) ctable[coordinates[0]][coordinates[1]]["possibilities"] = [elem] # print_table(ctable) # print return solve(ctable) except InvalidTableException: pass # print "subiu" raise InvalidTableException("Nao ha solucao") def _is_done(table): for line in table: for elem in line: if len(elem["possibilities"]) > 1: return False elif len(elem["possibilities"]) == 0: raise InvalidTableException("Celula Vazia") return True def _check_table(table): #find unchecked #clean other possibilities #raise exception if some possibility becomes void while not _is_check_done(table): unchecked_set = _find_unchecked(table) for value,x,y in unchecked_set: _fix_house(table,value,x,y) _fix_column(table,value,x,y) _fix_line(table,value,x,y) table[y][x]["checked"] = True return table def _is_check_done(table): for line in table: for elem in line: if len(elem["possibilities"]) == 1 and not elem["checked"]: return False return True def _find_unchecked(table): result = set() for i, line in enumerate(table): for j, elem in enumerate(line): if len(elem["possibilities"]) == 1 and not elem["checked"]: result.add((elem["possibilities"][0],j,i)) return result def _fix_house(table,value,x,y): x0 = (x/3)*3 + 1 y0 = (y/3)*3 + 1 to_fix = [(x0-1,y0-1),(x0-1,y0),(x0-1,y0+1),(x0,y0-1),(x0,y0),(x0,y0+1),(x0+1,y0-1),(x0+1,y0),(x0+1,y0+1)] to_fix.remove((x,y)) for i,j in to_fix: _fix(table,value,i,j) def _fix_column(table,value,x,y): columns = range(len(table)) columns.remove(y) for j in columns: _fix(table,value,x,j) def _fix_line(table,value,x,y): lines = range(len(table)) lines.remove(x) for i in lines: _fix(table,value,i,y) def _fix(table, value, x, y): try: table[y][x]["possibilities"].remove(value) except ValueError: pass if len(table[y][x]["possibilities"]) < 1: raise InvalidTableException("Nao deu!") def _get_minimum_array(table): result = list() size = len(table) for i, line in enumerate(table): for j, elem in enumerate(line): if not elem["checked"]: if not result: result.append((i,j)) size = len(elem["possibilities"]) elif len(elem["possibilities"]) == size: result.append((i,j)) elif len(elem["possibilities"]) < size: result = list() result.append((i,j)) size = len(elem["possibilities"]) return choice(result)
jonasrla/web_sudoku
helper/solver.py
Python
gpl-2.0
3,362