Search Results

Search found 137 results on 6 pages for 'ceil'.

Page 4/6 | < Previous Page | 1 2 3 4 5 6  | Next Page >

  • This pagination script is doodoo - I need a better one!

    - by ClarkSKent
    Hello, I was looking at the pagination script (posted below) and found it to be gros,s and not very good at all especially when trying to customize it. This is what the main page looks like: <?php include('config.php'); $per_page = 9; //Calculating no of pages $sql = "select * from messages"; $result = mysql_query($sql); $count = mysql_num_rows($result); $pages = ceil($count/$per_page) ?> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/ libs/jquery/1.3.0/jquery.min.js"></script> <script type="text/javascript" src="jquery_pagination.js"></script> <div id="loading" ></div> <div id="content" ></div> <ul id="pagination"> <?php //Pagination Numbers for($i=1; $i<=$pages; $i++) { echo '<li id="'.$i.'">'.$i.'</li>'; } ?> </ul> The top part of the code gets the results from the mysql db and than uses this information to display the numbers in the body of this page. I am trying to put something like this on a separate page like count_page.php and then just include it. I guess my question is, if there is a better way of doing the above with better structure. A better way to go through the db and count the results and display the appropriate numbers. The above seems messy. Thanks for any help or suggestions on this.

    Read the article

  • rookie MySql question about paging; Is one query enough?

    - by Camran
    I have managed to get paging to work, almost. I want to display to the user, total nr of records found, and the currently displayed records. Ex: 4000 found, displaying 0-100. I am testing this with the nr 2 (because I don't have that many records, have like 20). So I am using LIMIT $start, $nr_results; Do I have to make two queries in order to display the results the way I want, one query fetching all records and then make a mysql_num_rows to get all records, then the one with the LIMIT ? I have this: mysql_num_rows($qry_result); $total_pages = ceil($num_total / $res_per_page); //$res_per_page==2 and $num_total = 2 if ($p - 10 < 1) { $pagemin=1; } else { $pagemin = $p - 10; } if ($p + 10 $total_pages) { $pagemax = $total_pages; } else { $pagemax = $p + 10; } Here is the query: SELECT mt.*, fordon.*, boende.*, elektronik.*, business.*, hem_inredning.*, hobby.* FROM classified mt LEFT JOIN fordon ON fordon.classified_id = mt.classified_id LEFT JOIN boende ON boende.classified_id = mt.classified_id LEFT JOIN elektronik ON elektronik.classified_id = mt.classified_id LEFT JOIN business ON business.classified_id = mt.classified_id LEFT JOIN hem_inredning ON hem_inredning.classified_id = mt.classified_id LEFT JOIN hobby ON hobby.classified_id = mt.classified_id ORDER BY modify_date DESC LIMIT 0, 2 Thanks, if you need more input let me know. Basically Q is, do I have to make two queries?

    Read the article

  • select query from mysql_num_rows

    - by Andi Nugroho
    i want create multiple search where statement $where_search is a multiple condition from post form. but stil error when iam using this code ".where_search." in where condition with mysql_num_rows for paging $tampil2 = mysql_query("SELECT * FROM bb where ".$where_search." and kd_kelompok='2' and kd_komoditi='11' and nm_sebutan IS NOT NULL " ); this is the complete code. $where_search = "kd_pok='2' and kd_komoditi='11' "; if (isset($_POST['lakpus'])) { if (empty($_POST['lakpus'])) { } else { if (empty($where_search)) { $where_search .= "lakpus = '$lakpus' "; } else { $where_search .= "AND lakpus = '$lakpus' "; } } } if (isset($_POST['kd_por'])) { $kd_por = $_POST['kd_por'] ; if (empty($_POST['kd_por'])) { } else { if (empty($where_search)) { $where_search .= "kd_por = '$kd_por' "; } else { $where_search .= "AND tab1.kd_por = '$kd_por' "; } } } $max=15; $tampil2 = mysql_query("SELECT * FROM bb where ".$where_search." and kd_kelompok='2' and kd_komoditi='11' and nm_sebutan IS NOT NULL " ); $jml = mysql_num_rows($tampil2); $jmlhal = ceil($jml/$max);

    Read the article

  • How to bind to another event after ajax call in jquery

    - by robert
    Hi, I'm creating a graph using flot javascript library. I have enabled clickable event and the div is binded to plotclick event. So, when a datapoint is clicked, an ajax call is made and the result is used to replace the current div. After this i need to bind the div to a new event. I tried to call bind, but it is still bound to old callback. When i call unbind and bind, the new callback is not called. var handleTeacherClick = function( event, pos, item ) { if( typeof item != "undefined" && item ) { var user_id = jQuery( 'input[name="id' + item.datapoint[0] + '"]' ).val(); jQuery.ajax({ type: 'POST', url: BASEPATH + 'index.php/ajax/home/latest', data: { "user_id": user_id }, dataType: 'json', success: function ( result ) { jQuery.plot(jQuery('#stats_prog'), result.progress_data, result.progress_options); jQuery.plot(jQuery('#stats_perf'), result.performance_data, result.performance_options); jQuery('.stats_title'). html('<span class="stats_title">'+ ' >> Chapter '+Math.ceil(item.datapoint[0])+'</span>'); jQuery('#stats_prog')./*unbind("plotclick").*/ bind('plotclick', statClickHandler ); jQuery('#stats_perf')./*unbind("plotclick"). */ bind( 'plotclick', statClickHandler ); }, }); } }

    Read the article

  • Array indexOf implementation for Internet Explorer

    - by Daemon
    There are plenty of solutions on how to get the indexOf implementation into the Array prototype so that it works under Internet Explorer, however I've stumbled upon an issue that doesn't seem to be addressed anywhere I've looked so far. Using the pretty well agreed upon implementation at MDC, I have the following code that's being problematic now: // indexOf support for IE (from MDC) if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(elt /*, from*/) { var len = this.length >>> 0; var from = Number(arguments[1]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) from += len; for (; from < len; from++) { if (from in this && this[from] === elt) return from; } return -1; }; } var i = [1,2,3,4]; for (j in i) { alert(i[j]); } I am expecting to receive 4 alerts, each one containing one of the elements of the array. In Firefox and Chrome, that's exactly what I see, however in IE8 I get an additional alert containing the indexOf function code. What can be done to avoid this?

    Read the article

  • Array indexOf implentation for Internet Explorer

    - by Daemon
    There are plenty of solutions on how to get the indexOf implementation into the Array prototype so that it works under Internet Explorer, however I've stumbled upon an issue that doesn't seem to be addressed anywhere I've looked so far. Using the pretty well agreed upon implementation at MDC, I have the following code that's being problematic now: // indexOf support for IE (from MDC) if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(elt /*, from*/) { var len = this.length >>> 0; var from = Number(arguments[1]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) from += len; for (; from < len; from++) { if (from in this && this[from] === elt) return from; } return -1; }; } var i = [1,2,3,4]; for (j in i) { alert(i[j]); } I am expecting to receive 4 alerts, each one containing one of the elements of the array. In Firefox and Chrome, that's exactly what I see, however in IE8 I get an additional alert containing the indexOf function code. What can be done to avoid this?

    Read the article

  • Random Movement in a Fixed Container

    - by James Barracca
    I'm looking to create something that can move randomly inside of a fixed div container. I love the way the object moves in this example that I found searching this website... http://jsfiddle.net/Xw29r/15/ The code on the jsfiddle contains the following: $(document).ready(function(){ animateDiv(); }); function makeNewPosition(){ // Get viewport dimensions (remove the dimension of the div) var h = $(window).height() - 50; var w = $(window).width() - 50; var nh = Math.floor(Math.random() * h); var nw = Math.floor(Math.random() * w); return [nh,nw]; } function animateDiv(){ var newq = makeNewPosition(); var oldq = $('.a').offset(); var speed = calcSpeed([oldq.top, oldq.left], newq); $('.a').animate({ top: newq[0], left: newq[1] }, speed, function(){ animateDiv(); }); }; function calcSpeed(prev, next) { var x = Math.abs(prev[1] - next[1]); var y = Math.abs(prev[0] - next[0]); var greatest = x > y ? x : y; var speedModifier = 0.1; var speed = Math.ceil(greatest/speedModifier); return speed; }? CSS: div.a { width: 50px; height:50px; background-color:red; position:fixed; }? However, I don't believe the code above constricts that object at all. I need my object to move randomly inside of a container that is let's say for now... 1200px in width and 500px in height. Can someone steer me in the right direction? I'm super new to coding so I'm having a hard time finding an answer on my own. Thanks so much! James

    Read the article

  • select2: "text is undefined" when getting json using ajax

    - by user3046715
    I'm having an issue when getting json results back to select2. My json does not return a result that has a "text" field so need to format the result so that select2 accepts "Name". This code works if the text field in the json is set to "text" but in this case, I cannot change the formatting of the json result (code outside my control). $("#e1").select2({ formatNoMatches: function(term) {return term +" does not match any items." }, ajax: { // instead of writing the function to execute the request we use Select2's convenient helper url: "localhost:1111/Items.json", dataType: 'jsonp', cache: true, quietMillis: 200, data: function (term, page) { return { q: term, // search term p: page, s: 15 }; }, results: function (data, page) { // parse the results into the format expected by Select2. var numPages = Math.ceil(data.total / 15); return {results: data.Data, numPages: numPages}; } } }); I have looked into the documentation and found some statements you can put into the results such as text: 'Name', but I am still getting "text is undefined". Thanks for any help.

    Read the article

  • How can I add dynamic text from a different table where primary key is a foreign key to adynamic table being shown?

    - by Jethro Tamares Doble
    I have here a dynamic table named tb_user with column region_id and institute_id and both ids are primary key of another table tb_region (with column region_name and region_id) and tb_institute (column institute_id and institute_name). I wanted to see region_name and institute_name instead of the ids. I've used this php script <?php echo $row_institute['institution_name']; ?> and query to collect data for tb_institute mysql_select_db($database_connection_ched, $connection_ched); $query_institution = "SELECT institute_id, institute_name FROM tb_institute"; $institution = mysql_query($query_institution, $connection_ched) or die(mysql_error()); $row_institution = mysql_fetch_assoc($institution); $totalRows_institution = mysql_num_rows($institution); but it seems not to display the correct name of id. query i used to collect data: mysql_select_db($database_connection_ched, $connection_ched); $query_notification = sprintf("SELECT * FROM tb_user WHERE status = 'inactive' ORDER BY date_register ASC", GetSQLValueString($colname_notification, "text")); $query_limit_notification = sprintf("%s LIMIT %d, %d", $query_notification, $startRow_notification, $maxRows_notification); $notification = mysql_query($query_limit_notification, $connection_ched) or die(mysql_error()); $row_notification = mysql_fetch_assoc($notification); if (isset($_GET['totalRows_notification'])) { $totalRows_notification = $_GET['totalRows_notification']; } else { $all_notification = mysql_query($query_notification); $totalRows_notification = mysql_num_rows($all_notification); } $totalPages_notification = ceil($totalRows_notification/$maxRows_notification)-1;

    Read the article

  • Referencing movie clips from within an actionscript class

    - by Ant
    Hi all, I have been given the task of adding a scoring system to various flash games. This simply involves taking input, adding functionality such as pausing and replaying and then outputting the score, time left etc. at the end. I've so far successfully edited two games. Both these games used the "actions" code on frames. The latest game I'm trying to do uses an actionscript class which makes it both easier and harder. I'm not very adept at flash at all, but I've worked it out so far. I've added various movie clips that are to be used for displaying the pause screen background, buttons for replaying etc. I've been showing and hiding these using: back._visible = true; //movie clip, instance of back (back.png) I doubt it's best practice, but it's quick and has been working. However, now with the change of coding style to classes, this doesn't seem to work. I kinda understand why, but I'm now unsure how to hide/show these elements. Any help would be greatly appreciated :) I've attached the modified AS. class RivalOrbs extends MovieClip { var infinite_levels, orbs_start, orbs_inc, orbs_per_level, show_timer, _parent, one_time_per_level, speed_start, speed_inc_percent, max_speed, percent_starting_on_wrong_side, colorize, colors, secs_per_level; function RivalOrbs() { super(); mc = this; this.init(); } // End of the function function get_num_orbs() { if (infinite_levels) { return (orbs_start + (level - 1) * orbs_inc); } else if (level > orbs_per_level.length) { return (0); } else { return (orbs_per_level[level - 1]); } // end else if } // End of the function function get_timer_str(secs) { var _loc2 = Math.floor(secs / 60); var _loc1 = secs % 60; return ((_loc2 > 0 ? (_loc2) : ("0")) + ":" + (_loc1 >= 10 ? (_loc1) : ("0" + _loc1))); } // End of the function function frame() { //PLACE PAUSE CODE HERE if (!Key.isDown(80) and !Key.isDown(Key.ESCAPE)) { _root.offKey = true; } else if (Key.isDown(80) or Key.isDown(Key.ESCAPE)) { if (_root.offKey and _root.game_mode == "play") { _root.game_mode = "pause"; /* back._visible = true; btn_resume._visible = true; btn_exit._visible = true; txt_pause._visible = true; */ } else if (_root.offKey and _root.game_mode == "pause") { _root.game_mode = "play"; } _root.offKey = false; } if (_root.game_mode == "pause" or paused) { return; } else { /* back._visible = false; btn_resume._visible = false; btn_exit._visible = false; txt_pause._visible = false; */ } if (show_timer && total_secs != -1 || show_timer && _parent.timesup) { _loc7 = total_secs - Math.ceil((getTimer() - timer) / 1000); var diff = oldSeconds - (_loc7 + additional); if (diff > 1) additional = additional + diff; _loc7 = _loc7 + additional; oldSeconds = _loc7; trace(oldSeconds); mc.timer_field.text = this.get_timer_str(Math.max(0, _loc7)); if (_loc7 <= -1 || _parent.timesup) { if (one_time_per_level) { _root.gotoAndPlay("Lose"); } else { this.show_dialog(false); return; } // end if } // end if } // end else if var _loc9 = _root._xmouse; var _loc8 = _root._ymouse; var _loc6 = {x: _loc9, y: _loc8}; mc.globalToLocal(_loc6); _loc6.y = Math.max(-mc.bg._height / 2 + gap / 2, _loc6.y); _loc6.y = Math.min(mc.bg._height / 2 - gap / 2, _loc6.y); mc.wall1._y = _loc6.y - gap / 2 - mc.wall1._height / 2; mc.wall2._y = _loc6.y + gap / 2 + mc.wall1._height / 2; var _loc5 = true; for (var _loc4 = 0; _loc4 < this.get_num_orbs(); ++_loc4) { var _loc3 = mc.stage["orb" + _loc4]; _loc3.x_last = _loc3._x; _loc3.y_last = _loc3._y; _loc3._x = _loc3._x + _loc3.x_speed; _loc3._y = _loc3._y + _loc3.y_speed; if (_loc3._x < l_thresh) { _loc3.x_speed = _loc3.x_speed * -1; _loc3._x = l_thresh + (l_thresh - _loc3._x); _loc3.gotoAndPlay("hit"); } // end if if (_loc3._x > r_thresh) { _loc3.x_speed = _loc3.x_speed * -1; _loc3._x = r_thresh - (_loc3._x - r_thresh); _loc3.gotoAndPlay("hit"); } // end if if (_loc3._y < t_thresh) { _loc3.y_speed = _loc3.y_speed * -1; _loc3._y = t_thresh + (t_thresh - _loc3._y); _loc3.gotoAndPlay("hit"); } // end if if (_loc3._y > b_thresh) { _loc3.y_speed = _loc3.y_speed * -1; _loc3._y = b_thresh - (_loc3._y - b_thresh); _loc3.gotoAndPlay("hit"); } // end if if (_loc3.x_speed > 0) { if (_loc3._x >= m1_thresh && _loc3.x_last < m1_thresh || _loc3._x >= m1_thresh && _loc3._x <= m2_thresh) { if (_loc3._y <= mc.wall1._y + mc.wall1._height / 2 || _loc3._y >= mc.wall2._y - mc.wall2._height / 2) { _loc3.x_speed = _loc3.x_speed * -1; _loc3._x = m1_thresh - (_loc3._x - m1_thresh); _loc3.gotoAndPlay("hit"); } // end if } // end if } else if (_loc3._x <= m2_thresh && _loc3.x_last > m2_thresh || _loc3._x >= m1_thresh && _loc3._x <= m2_thresh) { if (_loc3._y <= mc.wall1._y + mc.wall1._height / 2 || _loc3._y >= mc.wall2._y - mc.wall2._height / 2) { _loc3.x_speed = _loc3.x_speed * -1; _loc3._x = m2_thresh + (m2_thresh - _loc3._x); _loc3.gotoAndPlay("hit"); } // end if } // end else if if (_loc3.side == 1 && _loc3._x > 0) { _loc5 = false; } // end if if (_loc3.side == 2 && _loc3._x < 0) { _loc5 = false; } // end if } // end of for if (_loc5) { this.end_level(); } // end if } // End of the function function colorize_hex(mc, hex) { var _loc4 = hex >> 16; var _loc5 = (hex ^ hex >> 16 << 16) >> 8; var _loc3 = hex >> 8 << 8 ^ hex; var _loc2 = new flash.geom.ColorTransform(0, 0, 0, 1, _loc4, _loc5, _loc3, 0); mc.transform.colorTransform = _loc2; } // End of the function function tint_hex(mc, hex, amount) { var _loc4 = hex >> 16; var _loc5 = hex >> 8 & 255; var _loc3 = hex & 255; this.tint(mc, _loc4, _loc5, _loc3, amount); } // End of the function function tint(mc, r, g, b, amount) { var _loc4 = 100 - amount; var _loc1 = new Object(); _loc1.ra = _loc1.ga = _loc1.ba = _loc4; var _loc2 = amount / 100; _loc1.rb = r * _loc2; _loc1.gb = g * _loc2; _loc1.bb = b * _loc2; var _loc3 = new Color(mc); _loc3.setTransform(_loc1); } // End of the function function get_num_levels() { if (infinite_levels) { return (Number.MAX_VALUE); } else { return (orbs_per_level.length); } // end else if } // End of the function function end_level() { _global.inputTimeAvailable = _global.inputTimeAvailable - (60 - oldSeconds); ++level; _parent.levelOver = true; if (level <= this.get_num_levels()) { this.show_dialog(true); } else { _root.gotoAndPlay("Win"); } // end else if } // End of the function function get_speed() { var _loc3 = speed_start; for (var _loc2 = 0; _loc2 < level - 1; ++_loc2) { _loc3 = _loc3 + _loc3 * (speed_inc_percent / 100); } // end of for return (Math.min(_loc3, Math.max(max_speed, speed_start))); } // End of the function function init_orbs() { var _loc6 = this.get_speed(); var _loc7 = Math.max(1, Math.ceil(this.get_num_orbs() * (percent_starting_on_wrong_side / 100))); for (var _loc3 = 0; _loc3 < this.get_num_orbs(); ++_loc3) { var _loc2 = null; if (_loc3 % 2 == 0) { _loc2 = mc.stage.attachMovie("Orb1", "orb" + _loc3, _loc3); _loc2.side = 1; if (colorize && color1 != -1) { this.colorize_hex(_loc2.orb.bg, color1); } // end if _loc2._x = Math.random() * (mc.bg._width * 4.000000E-001) - mc.bg._width * 2.000000E-001 - mc.bg._width / 4; } else { _loc2 = mc.stage.attachMovie("Orb2", "orb" + _loc3, _loc3); _loc2.side = 2; if (colorize && color2 != -1) { this.colorize_hex(_loc2.orb.bg, color2); } // end if _loc2._x = Math.random() * (mc.bg._width * 4.000000E-001) - mc.bg._width * 2.000000E-001 + mc.bg._width / 4; } // end else if _loc2._width = _loc2._height = orb_w; _loc2._y = Math.random() * (mc.bg._height * 8.000000E-001) - mc.bg._height * 4.000000E-001; if (_loc3 < _loc7) { _loc2._x = _loc2._x * -1; } // end if var _loc5 = Math.random() * 60; var _loc4 = _loc5 / 180 * 3.141593E+000; _loc2.x_speed = Math.cos(_loc4) * _loc6; _loc2.y_speed = Math.sin(_loc4) * _loc6; if (Math.random() >= 5.000000E-001) { _loc2.x_speed = _loc2.x_speed * -1; } // end if if (Math.random() >= 5.000000E-001) { _loc2.y_speed = _loc2.y_speed * -1; } // end if } // end of for } // End of the function function init_colors() { if (colorize && colors.length >= 2) { color1 = colors[Math.floor(Math.random() * colors.length)]; for (color2 = colors[Math.floor(Math.random() * colors.length)]; color2 == color1; color2 = colors[Math.floor(Math.random() * colors.length)]) { } // end of for this.tint_hex(mc.side1, color1, 40); this.tint_hex(mc.side2, color2, 40); } else { color1 = -1; color2 = -1; } // end else if } // End of the function function get_total_secs() { if (show_timer) { if (secs_per_level.length > 0) { if (level > secs_per_level.length) { return (secs_per_level[secs_per_level.length - 1]); } else { return (secs_per_level[level - 1]); } // end if } // end if } // end else if return (-1); } // End of the function function start_level() { trace ("start_level"); _parent.timesup = false; _parent.levelOver = false; _parent.times_up_comp.start_timer(); this.init_orbs(); mc.level_field.text = "LEVEL " + level; total_secs = _global.inputTimeAvailable; if (total_secs > 60) total_secs = 60; timer = getTimer(); paused = false; mc.dialog.gotoAndPlay("off"); } // End of the function function clear_orbs() { for (var _loc2 = 0; mc.stage["orb" + _loc2]; ++_loc2) { mc.stage["orb" + _loc2].removeMovieClip(); } // end of for } // End of the function function show_dialog(new_level) { mc.back._visible = false; trace("yes"); paused = true; if (new_level) { this.init_colors(); } // end if this.clear_orbs(); mc.dialog.gotoAndPlay("level"); if (!new_level || _parent.timesup) { mc.dialog.level_top.text = "Time\'s Up!"; /* dyn_line1.text = "Goodbye " + _global.inputName + "!"; dyn_line2.text = "You scored " + score; //buttons if (_global.inputTimeAvailable > 60) btn_replay._visible = true; btn_resume._visible = false; btn_exit._visible = false; txt_pause._visible = false; sendInfo = new LoadVars(); sendLoader = new LoadVars(); sendInfo.game_name = 'rival_orbs'; sendInfo.timeavailable = _global.inputTimeAvailable; if (sendInfo.timeavailable < 0) sendInfo.timeavailable = 0; sendInfo.id = _global.inputId; sendInfo.score = level*_global.inputFactor; sendInfo.directive = 'record'; //sendInfo.sendAndLoad('ncc1701e.aspx', sendLoader, "GET"); sendInfo.sendAndLoad('http://keyload.co.uk/output.php', sendLoader, "POST"); */ } else if (level > 1) { mc.dialog.level_top.text = "Next Level:"; } else { mc.dialog.level_top.text = ""; } // end else if mc.dialog.level_num.text = "LEVEL " + level; mc.dialog.level_mid.text = "Number of Orbs: " + this.get_num_orbs(); _root.max_level = level; var _this = this; mc.dialog.btn.onRelease = function () { _this.start_level(); }; } // End of the function function init() { var getInfo = new LoadVars(); var getLoader = new LoadVars(); getInfo.directive = "read"; getInfo.sendAndLoad('http://keyload.co.uk/input.php', getLoader, "GET"); getLoader.onLoad = function (success) { if (success) { _global.inputId = this.id; _global.inputTimeAvailable = this.timeavailable; _global.inputFactor = this.factor; _global.inputName = this.name; } else { trace("Failed"); } } _root.game_mode = "play"; /* back._visible = false; btn_exit._visible = false; btn_replay._visible = false; btn_resume._visible = false; txt_pause._visible = false; */ l_thresh = -mc.bg._width / 2 + orb_w / 2; t_thresh = -mc.bg._height / 2 + orb_w / 2; r_thresh = mc.bg._width / 2 - orb_w / 2; b_thresh = mc.bg._height / 2 - orb_w / 2; m1_thresh = -wall_w / 2 - orb_w / 2; m2_thresh = wall_w / 2 + orb_w / 2; this.show_dialog(true); mc.onEnterFrame = frame; } // End of the function var mc = null; var orb_w = 15; var wall_w = 2; var l_thresh = 0; var r_thresh = 0; var t_thresh = 0; var b_thresh = 0; var m1_thresh = 0; var m2_thresh = 0; var color1 = -1; var color2 = -1; var level = 1; var total_secs = 30; var gap = 60; var timer = 0; var additional = 0; var oldSeconds = 0; var paused = true; var _loc7 = 0; } // End of Class

    Read the article

  • Search option: jqGrid + PHP

    - by Felix Guerrero
    Hi, I'm trying to get work this code: $("#list").jqGrid({ url: 'docente.php', datatype: 'json', mtype: 'POST', postData: {c : "", n: "", a: "", d: "", t: "", e: "", f: "", g: $('#selectD').value(), p: "", call: "report"}, colNames: ['C&eacute;dula','Nombres', 'Apellidos', 'Direcci&oacute;n', 'E-mail','Tel&eacute;fono', 'Profesi&oacute;n'], colModel: [ { name:'rows.cedula', index: 'cedula', search:true, jsonmap: 'cedula', width: 150, align: 'left', sortable:true}, { name:'rows.nombre', index: 'nombre', jsonmap: 'nombre', width: 150, align: 'left'}, { name:'rows.apellido', index: 'apellido', jsonmap: 'apellido', width: 240, align: 'left'}, { name:'rows.direccion', index: 'direccion', jsonmap: 'direccion', width: 330, align: 'left'}, { name:'rows.email', index: 'email', jsonmap: 'email',width: 200, align: 'left'}, { name:'rows.telefono', index: 'telefono', jsonmap: 'telefono', width: 170, align: 'left'}, { name:'rows.descripcion_profesion', index: 'descripcion_profesion', jsonmap: 'descripcion_profesion',width: 120, align: 'left'}], pager: '#pager', rowNum: 8, autowidth: true, rowList: [10, 20], sortname: 'cedula', sortorder: 'asc', viewrecords: true, caption: 'Docentes', jsonReader : { root: "rows", repeatitems: false }, height: 350, width: 900 }); $("#list").jqGrid('navGrid','#pager',{search:true, searchtext: "buscar",edit:false,add:false,del:false}); The HMTL I'm using: <div id="reporte"> <table id="list"></table> <div id="pager"> </div> <div> And the PHP code: $total_pages = 0; $limit=10; $count = Profesor::CountAll(); if($count> 0) $total_pages= ceil($count/$limit); else $total_pages=0; $cnx = new PDO("mysql:host=localhost;dbname=appsms","root",""); $rows = array(); $strQuery="select cedula, nombre, apellido, direccion, telefono, email, descripcion_profesion from Profesor join Profesion on " . " (profesor.profesion_id = profesion.id) and (profesor.grado_id_grado = '" .$this->grado . "') order by cedula;"; $stmt = $cnx->prepare($strQuery); $stmt->execute(array("reporte")); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); $response->page = 1; $response->total= $total_pages; $response->records = sizeof($rows); $i=0; foreach($rows as $result){ $response->rows[$i] = $result; $i++; } echo json_encode($response); The JSON I get: {"page":1,"total":1,"records":2, "rows":[{"cedula":"v-108984103","nombre":"Soneia","apellido":"Rond\u00f3n Contreras","direccion":"El Rosal, calle 2-44","telefono":"04544247008457","email":"[email protected]","descripcion_profesion":"Docente"}, {"cedula":"v-135254741","nombre":"Judith","apellido":"Rangel M\u00e1rquez","direccion":"Sabaneta","telefono":"04247644152499","email":"","descripcion_profesion":"Docente"}]} It loads the query from PHP but the search option doesn't work neither the sorting function on "cedula"'s column. What I need to do?. Thanks in advance.

    Read the article

  • NSString drawAtPoint Crash on the iPhone (NSString drawAtPoint)

    - by Kyle
    Hey. I have a very simple text output to buffer system which will crash randomly. It will be fine for DAYS, then sometimes it'll crash a few times in a few minutes. The callstack is almost exactly the same for other guys who use higher level controls: http://discussions.apple.com/thread.jspa?messageID=7949746 http://stackoverflow.com/questions/1978997/iphone-app-crashed-assertion-failed-function-evictglyphentryfromstrike-file It crashes at the line (below as well in drawTextToBuffer()): [nsString drawAtPoint:CGPointMake(0, 0) withFont:clFont]; I have the same call of "evict_glyph_entry_from_cache" with the abort calls immediately following it. Apparently it happens to other people. I can say that my NSString* is perfectly fine at the time of the crash. I can read the text from the debugger just fine. static CGColorSpaceRef curColorSpace; static CGContextRef myContext; static float w, h; static int iFontSize; static NSString* sFontName; static UIFont* clFont; static int iLineHeight; unsigned long* txb; /* 256x256x4 Buffer */ void selectFont(int iSize, NSString* sFont) { iFontSize = iSize; clFont = [UIFont fontWithName:sFont size:iFontSize]; iLineHeight = (int)(ceil([clFont capHeight])); } void initText() { w = 256; h = 256; txb = (unsigned long*)malloc_(w * h * 4); curColorSpace = CGColorSpaceCreateDeviceRGB(); myContext = CGBitmapContextCreate(txb, w, h, 8, w * 4, curColorSpace, kCGImageAlphaPremultipliedLast); selectFont(12, @"Helvetica"); } void drawTextToBuffer(NSString* nsString) { CGContextSaveGState(myContext); CGContextSetRGBFillColor(myContext, 1, 1, 1, 1); UIGraphicsPushContext(myContext); /* This line will crash. It crashes even with constant Strings.. At the time of the crash, the pointer to nsString is perfectly fine. The data looks fine! */ [nsString drawAtPoint:CGPointMake(0, 0) withFont:clFont]; UIGraphicsPopContext(); CGContextRestoreGState(myContext); } It will happen with other non-unicode supporting methods as well such as CGContextShowTextAtPoint(); the callstack is similar with that as well. Is this any kind of known issue with the iPhone? Or, perhaps, can something outside of this cause be causing an exception in this particular call (drawAtPoint)?

    Read the article

  • Intent and OnActivityResult causing Activity to get restart Actuomatically : Require to solve this issues

    - by Parth Dani
    i am having 20 imageview and i am having 20 button for them when i click any 1 button it gives me option to select image from gallery or camera when i select any option for example galley it will take me to the gallery and let me select image from their and let me display those images on my imageview for respective button now the problem is sometimes when i do the whole above process my activity is getting restart actuomatically and all the image which were first selected get vanished from their imageview For Refernce my code is as follow: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.new_upload); // **************Code to get Road worthy number and VIN number value in // Shared Preference starts here************************ SharedPreferences myPrefs1 = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE); roadworthynumber = myPrefs1.getString(MY_ROADWORTHY, "Road Worthy Number"); vinnumber = myPrefs1.getString(MY_VIN, "VIN Number"); // **************Code to get Road worthy number and VIN number value in // Shared Preference ends here************************ // **************Code to create Directory AUSRWC starts // here************************ if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { cacheDir = new File(Environment.getExternalStorageDirectory() + File.separator + "AUSRWC" + File.separator); cacheDir.mkdirs(); } // **************Code to Create Directory AUSRWC ends // here************************ // *****************Assigning Button variable their Id declare in XML // file starts here***************** new_select1 = (Button) findViewById(R.id.new_select1); new_select2 = (Button) findViewById(R.id.new_select2); new_select3 = (Button) findViewById(R.id.new_select3); new_select4 = (Button) findViewById(R.id.new_select4); new_select5 = (Button) findViewById(R.id.new_select5); new_select6 = (Button) findViewById(R.id.new_select6); new_select7 = (Button) findViewById(R.id.new_select7); new_select8 = (Button) findViewById(R.id.new_select8); new_select9 = (Button) findViewById(R.id.new_select9); new_select10 = (Button) findViewById(R.id.new_select10); new_select11 = (Button) findViewById(R.id.new_select11); new_select12 = (Button) findViewById(R.id.new_select12); new_select13 = (Button) findViewById(R.id.new_select13); new_select14 = (Button) findViewById(R.id.new_select14); new_select15 = (Button) findViewById(R.id.new_select15); new_select16 = (Button) findViewById(R.id.new_select16); new_select17 = (Button) findViewById(R.id.new_select17); new_select18 = (Button) findViewById(R.id.new_select18); new_select19 = (Button) findViewById(R.id.new_select19); new_select20 = (Button) findViewById(R.id.new_select20); // *****************Assigning Button variable their Id declare in XML // file ends here***************** // *****************Assigning Image variable their Id declare in XML // file starts here***************** new_selectimage1 = (ImageView) findViewById(R.id.new_selectImage1); new_selectimage2 = (ImageView) findViewById(R.id.new_selectImage2); new_selectimage3 = (ImageView) findViewById(R.id.new_selectImage3); new_selectimage4 = (ImageView) findViewById(R.id.new_selectImage4); new_selectimage5 = (ImageView) findViewById(R.id.new_selectImage5); new_selectimage6 = (ImageView) findViewById(R.id.new_selectImage6); new_selectimage7 = (ImageView) findViewById(R.id.new_selectImage7); new_selectimage8 = (ImageView) findViewById(R.id.new_selectImage8); new_selectimage9 = (ImageView) findViewById(R.id.new_selectImage9); new_selectimage10 = (ImageView) findViewById(R.id.new_selectImage10); new_selectimage11 = (ImageView) findViewById(R.id.new_selectImage11); new_selectimage12 = (ImageView) findViewById(R.id.new_selectImage12); new_selectimage13 = (ImageView) findViewById(R.id.new_selectImage13); new_selectimage14 = (ImageView) findViewById(R.id.new_selectImage14); new_selectimage15 = (ImageView) findViewById(R.id.new_selectImage15); new_selectimage16 = (ImageView) findViewById(R.id.new_selectImage16); new_selectimage17 = (ImageView) findViewById(R.id.new_selectImage17); new_selectimage18 = (ImageView) findViewById(R.id.new_selectImage18); new_selectimage19 = (ImageView) findViewById(R.id.new_selectImage19); new_selectimage20 = (ImageView) findViewById(R.id.new_selectImage20); // ****Assigning Image variable their Id declare in XML file ends // here***************** // **************Creating Dialog to give option to user to new_select // image from gallery or from camera starts here**************** final String[] items = new String[] { "From Camera", "From Gallery" }; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, items); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("select Image"); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if (item == 0) { if (android.os.Environment.getExternalStorageState() .equals(android.os.Environment.MEDIA_MOUNTED)) { Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE); File file = new File(Environment .getExternalStorageDirectory(), "/AUSRWC/picture" + ".jpg"); mImageCaptureUri = Uri.fromFile(file); try { Toast.makeText(getBaseContext(), "Click Image", Toast.LENGTH_SHORT).show(); intent.putExtra( android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri); intent.putExtra("return-data", true); startActivityForResult(intent, PICK_FROM_CAMERA); } catch (Exception e) { e.printStackTrace(); } } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } dialog.cancel(); } else { Intent intent = new Intent(); Toast.makeText(getBaseContext(), "Select Image", Toast.LENGTH_SHORT).show(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE); } } }); dialog = builder.create(); // **************Creating Dialog to give option to user to new_select // image from gallery or from camera ends here**************** final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.anim_alpha); // Animation Code for displaying Button // Clicked. // ********************Image 1 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 1; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 1 button code ends // here******************************* // ********************Image 2 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 2; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 2 button code ends // here******************************* // ********************Image 3 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select3.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 3; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 3 button code ends // here******************************* // ********************Image 4 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select4.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 4; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 4 button code ends // here******************************* // ********************Image 5 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select5.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 5; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 5 button code ends // here******************************* // ********************Image 6 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select6.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 6; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 6 button code ends // here******************************* // ********************Image 7 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select7.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 7; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 7 button code ends // here******************************* // ********************Image 8 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select8.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 8; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 8 button code ends // here******************************* // ********************Image 9 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select9.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 9; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 9 button code ends // here******************************* // ********************Image 10 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select10.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 10; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 10 button code ends // here******************************* // ********************Image 11 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select11.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 11; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 11 button code ends // here******************************* // ********************Image 12 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select12.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 12; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 12 button code ends // here******************************* // ********************Image 13 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select13.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 13; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 13 button code ends // here******************************* // ********************Image 14 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select14.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 14; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 14 button code ends // here******************************* // ********************Image 15 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select15.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 15; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 15 button code ends // here******************************* // ********************Image 16 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select16.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 16; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 16 button code ends // here******************************* // ********************Image 17 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select17.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 17; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 17 button code ends // here******************************* // ********************Image 18 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select18.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 18; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 18 button code ends // here******************************* // ********************Image 19 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select19.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 19; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 19 button code ends // here******************************* // ********************Image 20 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select20.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 20; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 20 button code ends // here******************************* } // *************************When Back Button is Pressed code begins // here************************************* @Override public void onBackPressed() { Toast.makeText(new_upload.this, "Sorry You are not allowed to go back", Toast.LENGTH_SHORT).show(); return; } // *************************When Back Button is Pressed code ends // here************************************* // ***********************To get Path of new_selected Image code starts // here************************************ public String getRealPathFromURI(Uri contentUri) { String[] proj = { MediaStore.Images.Media.DATA }; Cursor cursor = managedQuery(contentUri, proj, null, null, null); if (cursor == null) return null; int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } // ***********************To get Path of new_selected Image code ends // here************************************ // **********************Picture obtained from the camera or from gallery // code starts here************** @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { //path = ""; Log.e("","requestCode="+requestCode); switch (requestCode){ case PICK_FROM_FILE: if (resultCode == Activity.RESULT_OK) { mImageCaptureUri = data.getData(); path = getRealPathFromURI(mImageCaptureUri); // from Gallery Log.e("", "Imagepath from gallery=" + path); if (path == null) path = mImageCaptureUri.getPath(); // from File Manager if (path != null) { dialog1 = ProgressDialog.show(new_upload.this, "", "Processing Please wait...", true); new ImageDisplayTask().execute(); } } break; case PICK_FROM_CAMERA: if (resultCode == Activity.RESULT_OK) { try { path = mImageCaptureUri.getPath(); Log.e("", "Imagepath from Camera =" + path); // bitmap = BitmapFactory.decodeFile(path); } catch (Exception e) { e.printStackTrace(); } if (path != null) { dialog1 = ProgressDialog.show(new_upload.this, "", "Processing Please wait...", true); //new ImageDisplayTask1().execute(); new ImageDisplayTask().execute(); } } break; default: } } // ********************Picture obtained from the camera or from gallery code // ends here********************************************* // ******************Image Display on Button when new_selected from gallery // Ashynch Code starts here******************************** class ImageDisplayTask extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... unsued) { Bitmap src = BitmapFactory.decodeFile(path); Bitmap dest = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888); //Bitmap dest = Bitmap.createScaledBitmap(src, src.getWidth(),src.getHeight(), true); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); String dateTime = sdf.format(Calendar.getInstance().getTime()); // reading local `` String timestamp = dateTime + " " + roadworthynumber; SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); String dateTime1 = sdf1.format(Calendar.getInstance().getTime()); Imagename = dateTime1.toString().trim().replaceAll(":", "") .replaceAll("-", "").replaceAll(" ", "") + roadworthynumber + ".jpg"; Canvas cs = new Canvas(dest); Paint tPaint = new Paint(); tPaint.setTextSize(100); tPaint.setTypeface(Typeface.SERIF); tPaint.setColor(Color.RED); tPaint.setStyle(Style.FILL); cs.drawBitmap(src, 0f, 0f, null); float height = tPaint.measureText("yY"); cs.drawText(timestamp, 5f, src.getHeight() - height + 5f, tPaint); try { dest.compress(Bitmap.CompressFormat.JPEG, 70, new FileOutputStream(new File(cacheDir, Imagename))); dest.recycle(); src.recycle(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onProgressUpdate(Void... unsued) { } @Override protected void onPostExecute(String serverresponse) { String error = "noerror"; Display currentDisplay = getWindowManager().getDefaultDisplay(); int dw = currentDisplay.getWidth(); int dh = currentDisplay.getHeight() - 100; Log.e("", "width= " + dw + " Height= " + dh); try { BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options(); bmpFactoryOptions.inJustDecodeBounds = true; Bitmap bmp = BitmapFactory.decodeFile( Environment.getExternalStorageDirectory() + "/AUSRWC/" + Imagename, bmpFactoryOptions); int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight / (float) dh); int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth / (float) dw); if (heightRatio > 1 && widthRatio > 1) { if (heightRatio > widthRatio) { bmpFactoryOptions.inSampleSize = heightRatio; } else { bmpFactoryOptions.inSampleSize = widthRatio; } } bmpFactoryOptions.inJustDecodeBounds = false; bmp = BitmapFactory.decodeFile( Environment.getExternalStorageDirectory() + "/AUSRWC/" + Imagename, bmpFactoryOptions); if (buttonpressed == 1) { new_selectimage1.setImageBitmap(bmp); //Image set on ImageView } else if (buttonpressed == 2) { new_selectimage2.setImageBitmap(bmp);//Image set on ImageView } else if (buttonpressed == 3) { new_selectimage3.setImageBitmap(bmp);//Image set on ImageView } else if (buttonpressed == 4) { new_selectimage4.setImageBitmap(bmp);//Image set on ImageView } else if (buttonpressed == 5) { new_selectimage5.setImageBitmap(bmp);//Image set on ImageView } else if (buttonpressed == 6) { new_selectimage6.setImageBitmap(bmp);//Image set on ImageView } else if (buttonpressed == 7) { new_selectimage7.setImageBitmap(bmp);//Image set on ImageView } else if (buttonpressed == 8) { new_selectimage8.setImageBitmap(bmp);//Image set on ImageView } else if (buttonpressed == 9) { new_selectimage9.setImageBitmap(bmp);//Image set on ImageView } else if (buttonpressed == 10) { new_selectimage10.setImageBitmap(bmp); } else if (buttonpressed == 11) { new_selectimage11.setImageBitmap(bmp); } else if (buttonpressed == 12) { new_selectimage12.setImageBitmap(bmp); } else if (buttonpressed == 13) { new_selectimage13.setImageBitmap(bmp); } else if (buttonpressed == 14) { new_selectimage14.setImageBitmap(bmp); } else if (buttonpressed == 15) { new_selectimage15.setImageBitmap(bmp); } else if (buttonpressed == 16) { new_selectimage16.setImageBitmap(bmp); } else if (buttonpressed == 17) { new_selectimage17.setImageBitmap(bmp); } else if (buttonpressed == 18) { new_selectimage18.setImageBitmap(bmp); } else if (buttonpressed == 19) { new_selectimage19.setImageBitmap(bmp); } else if (buttonpressed == 20) { new_selectimage20.setImageBitmap(bmp); } } catch (Exc

    Read the article

  • How does MySQL's ORDER BY RAND() work?

    - by Eugene
    Hi, I've been doing some research and testing on how to do fast random selection in MySQL. In the process I've faced some unexpected results and now I am not fully sure I know how ORDER BY RAND() really works. I always thought that when you do ORDER BY RAND() on the table, MySQL adds a new column to the table which is filled with random values, then it sorts data by that column and then e.g. you take the above value which got there randomly. I've done lots of googling and testing and finally found that the query Jay offers in his blog is indeed the fastest solution: SELECT * FROM Table T JOIN (SELECT CEIL(MAX(ID)*RAND()) AS ID FROM Table) AS x ON T.ID >= x.ID LIMIT 1; While common ORDER BY RAND() takes 30-40 seconds on my test table, his query does the work in 0.1 seconds. He explains how this functions in the blog so I'll just skip this and finally move to the odd thing. My table is a common table with a PRIMARY KEY id and other non-indexed stuff like username, age, etc. Here's the thing I am struggling to explain SELECT * FROM table ORDER BY RAND() LIMIT 1; /*30-40 seconds*/ SELECT id FROM table ORDER BY RAND() LIMIT 1; /*0.25 seconds*/ SELECT id, username FROM table ORDER BY RAND() LIMIT 1; /*90 seconds*/ I was sort of expecting to see approximately the same time for all three queries since I am always sorting on a single column. But for some reason this didn't happen. Please let me know if you any ideas about this. I have a project where I need to do fast ORDER BY RAND() and personally I would prefer to use SELECT id FROM table ORDER BY RAND() LIMIT 1; SELECT * FROM table WHERE id=ID_FROM_PREVIOUS_QUERY LIMIT 1; which, yes, is slower than Jay's method, however it is smaller and easier to understand. My queries are rather big ones with several JOINs and with WHERE clause and while Jay's method still works, the query grows really big and complex because I need to use all the JOINs and WHERE in the JOINed (called x in his query) sub request. Thanks for your time!

    Read the article

  • Problem in loading cities using JSON

    - by Saravanan I M
    I am using Geonames for loading the cities using JSON. Geonames data i imported into my database. I am using MS SQL 2008 Server. I display a dropdown for country select. Once the user select the country. I am loading all the cities into the autocomplete textbox. I am facing a delay in the getJSON method. Also it seems like executing asynchronous. So before getting all the data my autocompelte is getting filled. Below is my complete script. I think i have some problem in the loop. Please advice me what i am doing wrong in my code. $(document).ready(function () { $("#ShowLoad").hide(); //Hook onto the MakeID list's onchange event $("#Country").change(function () { findcities = []; $("#ShowLoad").show(); $("#HomeTown").unautocomplete(); var url = '<%= Url.Content("~/") %>' + "Location/GetCitiesCountByCountry/" + $("#Country").val(); $.getJSON(url, null, function (data) { var total = data; if (total > 0) { var pageTotal = Math.ceil(total / 1000); var isFilled = false; for (var i = 0; i < pageTotal; i++) { var skip = i == 1 ? 0 : (i * 1000) - 1000; var url = '<%= Url.Content("~/") %>' + "Location/GetCitiesByCountry/" + $("#Country").val() + "?skip=" + skip; //alert(i); $.getJSON(url, null, function (data) { $.each(data.Cities, function (index, optionData) { if ($("#Country").val() == "US") { findcities.push(optionData.asciiname + "," + optionData.admin1_code); } else { findcities.push(optionData.asciiname); } }); if (i == pageTotal) { //alert(findcities); $("#ShowLoad").hide(); $("#HomeTown").focus().autocomplete(findcities); } }); } $("#HomeTown").setOptions({ max: 100000 }); } }); }).change(); });

    Read the article

  • Background-image won't change using jquery in IE6

    - by slav
    There is a panel on my page with no default background-image css. On load it is set with jquery to an initial image, waits for 10 seconds then loads a random image out of some predetermined images. There are previous and next buttons which allow you to cycle through the images. In ie6 the initial image loads and then a random image also loads after 10 seconds, however pressing prev/next causes the background to become white and the images aren't loaded. With alerts I was able to find that it's still keeping track of the position and url of the image it's supposed to load, but just won't load it. Here is the code below. <script type="text/javascript"> var facts = new Array(); var position; $(document).ready(function() { <xsl:for-each select="$currentPage/ancestor-or-self::node[@level=1]/../node[@nodeName='Fun Fact Folder']/node"> facts[<xsl:value-of select="position()" />] = '<xsl:value-of select="." />'; </xsl:for-each> if(window.location.pathname == "/homepage.aspx" || window.location.pathname == "/") { $(".fun_facts_bg").css("background-image", "url(images/fun_fact_homepage.JPG)"); setTimeout("randomFact()",10000); } else { randomFact(); } }); function randomFact() { $("a.previous_button").css("display", "block"); $("a.next_button").css("display", "block"); position = Math.ceil(Math.random() * (facts.length - 1)); changeFact(0); } function changeFact(increment) { position = checkPosition(position, increment); $(".fun_facts_bg").css("background-image", "url(" + facts[position] + ")"); } <xsl:text disable-output-escaping="yes">&lt;!--//--&gt;&lt;![CDATA[//&gt;&lt;!-- function checkPosition(currentPos, increment) { currentPos = currentPos + increment; if (currentPos &gt; facts.length - 1) { currentPos = 1; } else if (currentPos &lt; 1) { currentPos = facts.length - 1; } return currentPos; } //--&gt;&lt;!]]&gt;</xsl:text> </script> <a class="previous_button" href="javascript:void(0);" onclick="changeFact(-1);"> <a class="next_button" href="javascript:void(0);" onclick="changeFact(1);">

    Read the article

  • adding other parameter to function

    - by Ronnie Chester Lynwood
    hello. i got a function that listing downloads in a table with foreach. it's also lists searched term, search type. public function fetchDownloads($displaySite=true) { $downloads = array(); $sqlWhere = ""; if(isset($this->q)) { if(strlen($this->q) <= $this->recents_length && !empty($this->q)) { $insertRecent = $this->processDataHook("insertRecent",$this->q); if($insertRecent) { if(!@mysql_query("INSERT INTO wcddl_recents (query) VALUES ('".$this->qSQL."')")) { @mysql_query("UPDATE wcddl_recents SET searches = searches+1 WHERE query = '".$this->qSQL."'"); } } } if($this->search_type == "narrow") { $sqlWhere = " WHERE title LIKE '%".mysql_real_escape_string(str_replace(" ","%",$this->q))."%'"; } elseif($this->search_type == "wide") { $qExp = explode(" ",$this->q); $sqlWhere = array(); foreach($qExp as $fq) $sqlWhere[] = "title LIKE '%".mysql_real_escape_string($fq)."%'"; $sqlWhere = implode(" OR ",$sqlWhere); $sqlWhere = " WHERE (".$sqlWhere.")"; } } if(isset($this->type)) { if(!empty($sqlWhere)) { $sqlWhere .= " AND type = '".$this->typeSQL."'"; } else { $sqlWhere = " WHERE type = '".$this->typeSQL."'"; } } $sqlWhere = $this->processDataHook("fetchDownloadsSQLWhere",$sqlWhere); $this->maxPages = mysql_query("SELECT COUNT(*) FROM wcddl_downloads".$sqlWhere.""); $this->maxPages = mysql_result($this->maxPages,0); $this->numRows = $this->maxPages; $this->maxPages = ceil($this->maxPages/$this->limit); $sqlMain = "SELECT id,sid,title,type,url,dat,views,rating FROM wcddl_downloads".$sqlWhere." ORDER BY ".(isset($this->sqlOrder) ? mysql_real_escape_string($this->sqlOrder) : "id DESC")." LIMIT ".$this->pg.",".$this->limit.""; $sqlMain = $this->processDataHook("whileFetchDownloadsSQL",$sqlMain); $sqlMain = mysql_query($sqlMain); $this->processHook("whileFetchDownloads"); while($row = mysql_fetch_assoc($sqlMain)) { if($displaySite) { $downloadSite = mysql_query("SELECT name as sname, url as surl, rating as srating FROM wcddl_sites WHERE id = '".$row['sid']."'"); $downloadSite = mysql_fetch_assoc($downloadSite); $row = array_merge($row,$downloadSite); } $downloads_current = $this->mapit($row,array("stripslashes","strip_tags")); $downloads_current = $this->processDataHook("fetchDownloadsRow",$downloads_current); $downloads[] = $downloads_current; } $this->pageList = $this->getPages($this->page,$this->maxPages); $this->processHook("endFetchDownloads"); return $downloads; } I want to add if $_REQUEST['site'] is set, order downloads by sname that catching from wcddl_sites.

    Read the article

  • Copying metadata over a database link in Oracle 10g

    - by Tunde
    Thanks in advance for your help experts. I want to be able to copy over database objects from database A into database B with a procedure created on database B. I created a database link between the two and have tweaked the get_ddl function of the dbms_metadata to look like this: create or replace function GetDDL ( p_name in MetaDataPkg.t_string p_type in MetaDataPkg.t_string ) return MetaDataPkg.t_longstring is -- clob v_clob clob; -- array of long strings c_SYSPrefix constant char(4) := 'SYS_'; c_doublequote constant char(1) := '"'; v_longstrings metadatapkg.t_arraylongstring; v_schema metadatapkg.t_string; v_fullength pls_integer := 0; v_offset pls_integer := 0; v_length pls_integer := 0; begin SELECT DISTINCT OWNER INTO v_schema FROM all_objects@ENTORA where object_name = upper(p_name); -- get DDL v_clob := dbms_metadata.get_ddl(p_type, upper(p_name), upper(v_schema)); -- get CLOB length v_fullength := dbms_lob.GetLength(v_clob); for nIndex in 1..ceil(v_fullength / 32767) loop v_offset := v_length + 1; v_length := least(v_fullength - (nIndex - 1) * 32767, 32767); dbms_lob.read(v_clob, v_length, v_offset, v_longstrings(nIndex)); -- Remove table’s owner from DDL string: v_longstrings(nIndex) := replace( v_longstrings(nIndex), c_doublequote || user || c_doublequote || '.', '' ); -- Remove the following from DDL string: -- 1) "new line" characters (chr(10)) -- 2) leading and trailing spaces v_longstrings(nIndex) := ltrim(rtrim(replace(v_longstrings(nIndex), chr(10), ''))); end loop; -- close CLOB if (dbms_lob.isOpen(v_clob) > 0) then dbms_lob.close(v_clob); end if; return v_longstrings(1); end GetDDL; so as to remove the schema prefix that usually comes with metadata. I get a null value whenever I run this function over the database link with the following queries. select getddl( 'TABLE', 'TABLE1') from user_tables@ENTORA where table_name = 'TABLE1'; select getddl( 'TABLE', 'TABLE1') from dual@ENTORA; t_string is varchar2(30) t_longstring is varchar2(32767) and type t_ArrayLongString is table of t_longstring I would really appreciate it if any one could help. Many thanks.

    Read the article

  • Ajax, php, mysql not working mysql limit

    - by Hofmeister Ákos
    I have 3 files. list.php $articles = $mysqli->query("SELECT mainPictureBig, title, writer, writeDate, link FROM articles WHERE category=$this->category ORDER BY writeDate DESC LIMIT 0,10"); while($article = mysqli_fetch_row($articles)) { echo "<a href=\"".$this->url."/".$article[3]."/".$article[4]."\"><div id=\"listElement\"> <div id=\"listElementWallpaper\" style=\"background-image: url('category/img.jpg');\"></div> <div id=\"listElementContent\"><div id=\"listElementTitle\">".$article[1]."</div>".$this->giveWriter($article[2]).", ".$this->giveDate($article[3])."</div> </div></a>"; } $maximumElements=ceil($numberOfContent / 10) * 10; It's working, so there is no problem, it lists the first 10 elements from the sql table, and i got the $numberOfCOntent part also. Than i have a button: echo "<div id=\"listMore\"><div id=\"buttonOne\" onclick=\"listMore($this->category,$maximumElements)\">Load more</div></div>"; There is also no problem, i load the .js file, and it looks like: var from = 10; function listMore(categoryId, maximum) { $( "#listMore" ).slideUp( 200, function() { $( "#listMore" ).html("<center>Loading..</center>"); $( "#listMore" ).slideDown( 500, function() { $.post( "http://localhost/ajax.php", {type: "listMore", id: categoryId, sqlFrom: from} ) .done(function( elements ) { $("#listBody").append( elements ); if(maximum > from+10) { from = from+10; $( "#listMore" ).slideUp(200, function() { $( "#listMore" ).html("<div id=\"buttonOne\" onclick=\"listMore("+categoryId+","+maximum+")\">Load more</div>"); $( "#listMore" ).slideDown(200); }); } else $( "#listMore" ).slideUp(200); }); }); }); } And it's also working, and the problem is in the PHP file. As you can see, i'm sending an integer the "from" variable, the PHP file: $articles = $mysqli->query("SELECT mainPictureBig, title, writer, writeDate, link FROM articles WHERE category=$id ORDER BY writeDate DESC LIMIT $from,10"); It's also working, but not loading the next 10, only the next 9. So it skips the very next row and loads the rows only after the very first, so only 9. I tried to write here only the important part of the code, so i skipped some echo part etc. Any idea?

    Read the article

  • Jquery help : How to implement a Previous/Next & Play/Pause toggle for this script

    - by rameshelamathi
    (function($){ // Creating the sweetPages jQuery plugin: $.fn.sweetPages = function(opts){ // If no options were passed, create an empty opts object if(!opts) opts = {}; var resultsPerPage = opts.perPage || 3; var swDiv = opts.getSwDiv || "swControls"; // The plugin works best for unordered lists, althugh ols would do just as well: var ul = this; var li = ul.find('li'); li.each(function(){ // Calculating the height of each li element, and storing it with the data method: var el = $(this); el.data('height',el.outerHeight(true)); }); // Calculating the total number of pages: var pagesNumber = Math.ceil(li.length/resultsPerPage); // If the pages are less than two, do nothing: if(pagesNumber<2) return this; // Creating the controls div: //var swControls = $('<div class="swControls">'); var swControls = $('<div class='+swDiv+'>'); for(var i=0;i<pagesNumber;i++) { // Slice a portion of the lis, and wrap it in a swPage div: li.slice(i*resultsPerPage,(i+1)*resultsPerPage).wrapAll('<div class="swPage" />'); // Adding a link to the swControls div: swControls.append('<a href="" class="swShowPage">'+(i+1)+'</a>'); } ul.append(swControls); var maxHeight = 0; var totalWidth = 0; var swPage = ul.find('.swPage'); swPage.each(function(){ // Looping through all the newly created pages: var elem = $(this); var tmpHeight = 0; elem.find('li').each(function(){tmpHeight+=$(this).data('height');}); if(tmpHeight>maxHeight) maxHeight = tmpHeight; totalWidth+=elem.outerWidth(); elem.css('float','left').width(ul.width()); }); swPage.wrapAll('<div class="swSlider" />'); // Setting the height of the ul to the height of the tallest page: //ul.height(maxHeight); var swSlider = ul.find('.swSlider'); swSlider.append('<div class="clear" />').width(totalWidth); var hyperLinks = ul.find('a.swShowPage'); hyperLinks.click(function(e){ // If one of the control links is clicked, slide the swSlider div // (which contains all the pages) and mark it as active: $(this).addClass('active').siblings().removeClass('active'); swSlider.stop().animate({'margin-left':-(parseInt($(this).text())-1)*ul.width()},'slow'); e.preventDefault(); }); // Mark the first link as active the first time this code runs: hyperLinks.eq(0).addClass('active'); // Center the control div: swControls.css({ 'right':'10%', 'margin-left':-swControls.width()/2 }); return this; }})(jQuery);

    Read the article

  • pagination - 10 pages per page

    - by arthur
    I have a pagination script that displays a list of all pages like so: prev [1][2][3][4][5][6][7][8][9][10][11][12][13][14] next But I would like to only show ten of the numbers at a time: prev [3][4][5][6][7][8][9][10][11][12] next How can I accomplish this? Here is my code so far: <?php /* Set current, prev and next page */ $page = (!isset($_GET['page']))? 1 : $_GET['page']; $prev = ($page - 1); $next = ($page + 1); /* Max results per page */ $max_results = 2; /* Calculate the offset */ $from = (($page * $max_results) - $max_results); /* Query the db for total results. You need to edit the sql to fit your needs */ $result = mysql_query("select title from topics"); $total_results = mysql_num_rows($result); $total_pages = ceil($total_results / $max_results); $pagination = ''; /* Create a PREV link if there is one */ if($page > 1) { $pagination .= '< a hr_ef="?page='.$prev.'">Previous</a> '; } /* Loop through the total pages */ for($i = 1; $i <= $total_pages; $i++) { if(($page) == $i) { $pagination .= $i; } else { $pagination .= '< a hr_ef="index.php?page='.$i.'">'.$i.'</a>'; } } /* Print NEXT link if there is one */ if($page < $total_pages) { $pagination .= '< a hr_ef="?page='.$next.'"> Next</a>'; } /* Now we have our pagination links in a variable($pagination) ready to print to the page. I pu it in a variable because you may want to show them at the top and bottom of the page */ /* Below is how you query the db for ONLY the results for the current page */ $result=mysql_query("select * from topics LIMIT $from, $max_results "); while ($i = mysql_fetch_array($result)) { echo $i['title'].'<br />'; } echo $pagination; ?>

    Read the article

  • how can i do pagination without reaload page in wordpress

    - by Swap
    how can i do pagination without reaload page in wordpress. i have use following code for the pagination but here page is reaload for each pagination. what can i do to stop realod page???please suggest me. <?php $page = (get_query_var('page')) ? get_query_var('page') : 1 $limit=10; $offset = ( $page - 1 ) * $limit; $data = $wpdb->get_results("select * from wp_products order by product_id $sort_by LIMIT $offset,$limit "); $total=$wpdb->get_results("select * from wp_products "); $pages = COUNT($total); $pages = ceil($pages / $limit); $querystring = ""; foreach ($_GET as $key => $value) { if ($key != "page") $querystring .= "$key=$value&amp;"; } // Pagination ?> <div class="pagination"> <?php if( $pages > 1) { $range=1; $showitems = ($range * 2)+1; $page1=$page; $prev=$page1-1; if($page > 1) { echo "<a class=\"page gradient\" "; echo "href=\"?{$querystring}page=$prev"; echo "\">Previous</a> "; } for ($i = 1; $i <= $pages; $i++) { if (1 != $pages &&( !($i >= $page+$range+1 || $i <= $page-$range-1) || $pages <= $showitems )) { if($i == $page) { echo "<span class=\" page active\">".$i."</span>"; } else { echo "<a class=\"page gradient\""; echo "href=\"?{$querystring}page=$i"; echo "\">$i</a> "; } } } if($page!=$pages) { if($showitems < $pages) { echo "..... "; } $page1=$page; $next=$page1+1; echo "<a " . ($i == $page ? "class=\"page active\" " : "class=\"page gradient\""); echo "href=\"?{$querystring}page=$next"; echo "\">Next</a> "; } } ?> </div>

    Read the article

  • Who could ask for more with LESS CSS? (Part 3 of 3&ndash;Clrizr)

    - by ToString(theory);
    Welcome back!  In the first two posts in this series, I covered some of the awesome features in CSS precompilers such as SASS and LESS, as well as how to get an initial project setup up and running in ASP.Net MVC 4. In this post, I will cover an actual advanced example of using LESS in a project, and show some of the great productivity features we gain from its usage. Introduction In the first post, I mentioned two subjects that I will be using in this example – constants, and color functions.  I’ve always enjoyed using online color scheme utilities such as Adobe Kuler or Color Scheme Designer to come up with a scheme based off of one primary color.  Using these tools, and requesting a complementary scheme you can get a couple of shades of your primary color, and a couple of shades of a complementary/accent color to display. Because there is no way in regular css to do color operations or store variables, there was no way to accomplish something like defining a primary color, and have a site theme cascade off of that.  However with tools such as LESS, that impossibility becomes a reality!  So, if you haven’t guessed it by now, this post is on the creation of a plugin/module/less file to drop into your project, plugin one color, and have your primary theme cascade from it.  I only went through the trouble of creating a module for getting Complementary colors.  However, it wouldn’t be too much trouble to go through other options such as Triad or Monochromatic to get a module that you could use off of that. Step 1 – Analysis I decided to mimic Adobe Kuler’s Complementary theme algorithm as I liked its simplicity and aesthetics.  Color Scheme Designer is great, but I do believe it can give you too many color options, which can lead to chaos and overload.  The first thing I had to check was if the complementary values for the color schemes were actually hues rotated by 180 degrees at all times – they aren’t.  Apparently Adobe applies some variance to the complementary colors to get colors that are actually more aesthetically appealing to users.  So, I opened up Excel and began to plot complementary hues based on rotation in increments of 10: Long story short, I completed the same calculations for Hue, Saturation, and Lightness.  For Hue, I only had to record the Complementary hue values, however for saturation and lightness, I had to record the values for ALL of the shades.  Since the functions were too complicated to put into LESS since they aren’t constant/linear, but rather interval functions, I instead opted to extrapolate the HSL values using the trendline function for each major interval, onto intervals of spacing 1. For example, using the hue extraction, I got the following values: Interval Function 0-60 60-140 140-270 270-360 Saturation and Lightness were much worse, but in the end, I finally had functions for all of the intervals, and then went the route of just grabbing each shades value in intervals of 1.  Step 2 – Mapping I declared variable names for each of these sections as something that shouldn’t ever conflict with a variable someone would define in their own file.  After I had each of the values, I extracted the values and put them into files of their own for hue variables, saturation variables, and lightness variables…  Example: /*HUE CONVERSIONS*/@clrizr-hue-source-0deg: 133.43;@clrizr-hue-source-1deg: 135.601;@clrizr-hue-source-2deg: 137.772;@clrizr-hue-source-3deg: 139.943;@clrizr-hue-source-4deg: 142.114;.../*SATURATION CONVERSIONS*/@clrizr-saturation-s2SV0px: 0;@clrizr-saturation-s2SV1px: 0;@clrizr-saturation-s2SV2px: 0;@clrizr-saturation-s2SV3px: 0;@clrizr-saturation-s2SV4px: 0;.../*LIGHTNESS CONVERSIONS*/@clrizr-lightness-s2LV0px: 30;@clrizr-lightness-s2LV1px: 31;@clrizr-lightness-s2LV2px: 32;@clrizr-lightness-s2LV3px: 33;@clrizr-lightness-s2LV4px: 34;...   In the end, I have 973 lines of mapping/conversion from source HSL to shade HSL for two extra primary shades, and two complementary shades. The last bit of the work was the file to compose each of the shades from these mappings. Step 3 – Clrizr Mapper The final step was the hardest to overcome as I was still trying to understand LESS to its fullest extent.  Imports As mentioned previously, I had separated the HSL mappings into different files, so the first necessary step is to import those for use into the Clrizr plugin: @import url("hue.less");@import url("saturation.less");@import url("lightness.less"); Extract Component Values For Each Shade Next, I extracted the necessary information for each shade HSL before shade composition: @clrizr-input-saturation: 1px+floor(saturation(@clrizr-input))-1;@clrizr-input-lightness: 1px+floor(lightness(@clrizr-input))-1; @clrizr-complementary-hue: formatstring("clrizr-hue-source-{0}", ceil(hue(@clrizr-input))); @clrizr-primary-2-saturation: formatstring("clrizr-saturation-s2SV{0}",@clrizr-input-saturation);@clrizr-primary-1-saturation: formatstring("clrizr-saturation-s1SV{0}",@clrizr-input-saturation);@clrizr-complementary-1-saturation: formatstring("clrizr-saturation-c1SV{0}",@clrizr-input-saturation); @clrizr-primary-2-lightness: formatstring("clrizr-lightness-s2LV{0}",@clrizr-input-lightness);@clrizr-primary-1-lightness: formatstring("clrizr-lightness-s1LV{0}",@clrizr-input-lightness);@clrizr-complementary-1-lightness: formatstring("clrizr-lightness-c1LV{0}",@clrizr-input-lightness); Here, you can see a couple of odd things…  On the first line, I am using operations to add units to the saturation and lightness.  This is due to some limitations in the operations that would give me saturation or lightness in %, which can’t be in a variable name.  So, I use first add 1px to it, which casts the result of the following functions as px instead of %, and then at the end, I remove that pixel.  You can also see here the formatstring method which is exactly what it sounds like – something like String.Format(string str, params object[] obj). Get Primary & Complementary Shades Now that I have components for each of the different shades, I can now compose them into each of their pieces.  For this, I use the @@ operator which will look for a variable with the name specified in a string, and then call that variable: @clrizr-primary-2: hsl(hue(@clrizr-input), @@clrizr-primary-2-saturation, @@clrizr-primary-2-lightness);@clrizr-primary-1: hsl(hue(@clrizr-input), @@clrizr-primary-1-saturation, @@clrizr-primary-1-lightness);@clrizr-primary: @clrizr-input;@clrizr-complementary-1: hsl(@@clrizr-complementary-hue, @@clrizr-complementary-1-saturation, @@clrizr-complementary-1-lightness);@clrizr-complementary-2: hsl(@@clrizr-complementary-hue, saturation(@clrizr-input), lightness(@clrizr-input)); That’s is it, for the most part.  These variables now hold the theme for the one input color – @clrizr-input.  However, I have one last addition… Perceptive Luminance Well, after I got the colors, I decided I wanted to also get the best font color that would go on top of it.  Black or white depending on light or dark color.  Now I couldn’t just go with checking the lightness, as that is half the story.  You see, the human eye doesn’t see ALL colors equally well but rather has more cells for interpreting green light compared to blue or red.  So, using the ratio, we can calculate the perceptive luminance of each of the shades, and get the font color that best matches it! @clrizr-perceptive-luminance-ps2: round(1 - ( (0.299 * red(@clrizr-primary-2) ) + ( 0.587 * green(@clrizr-primary-2) ) + (0.114 * blue(@clrizr-primary-2)))/255)*255;@clrizr-perceptive-luminance-ps1: round(1 - ( (0.299 * red(@clrizr-primary-1) ) + ( 0.587 * green(@clrizr-primary-1) ) + (0.114 * blue(@clrizr-primary-1)))/255)*255;@clrizr-perceptive-luminance-ps: round(1 - ( (0.299 * red(@clrizr-primary) ) + ( 0.587 * green(@clrizr-primary) ) + (0.114 * blue(@clrizr-primary)))/255)*255;@clrizr-perceptive-luminance-pc1: round(1 - ( (0.299 * red(@clrizr-complementary-1)) + ( 0.587 * green(@clrizr-complementary-1)) + (0.114 * blue(@clrizr-complementary-1)))/255)*255;@clrizr-perceptive-luminance-pc2: round(1 - ( (0.299 * red(@clrizr-complementary-2)) + ( 0.587 * green(@clrizr-complementary-2)) + (0.114 * blue(@clrizr-complementary-2)))/255)*255; @clrizr-col-font-on-primary-2: rgb(@clrizr-perceptive-luminance-ps2, @clrizr-perceptive-luminance-ps2, @clrizr-perceptive-luminance-ps2);@clrizr-col-font-on-primary-1: rgb(@clrizr-perceptive-luminance-ps1, @clrizr-perceptive-luminance-ps1, @clrizr-perceptive-luminance-ps1);@clrizr-col-font-on-primary: rgb(@clrizr-perceptive-luminance-ps, @clrizr-perceptive-luminance-ps, @clrizr-perceptive-luminance-ps);@clrizr-col-font-on-complementary-1: rgb(@clrizr-perceptive-luminance-pc1, @clrizr-perceptive-luminance-pc1, @clrizr-perceptive-luminance-pc1);@clrizr-col-font-on-complementary-2: rgb(@clrizr-perceptive-luminance-pc2, @clrizr-perceptive-luminance-pc2, @clrizr-perceptive-luminance-pc2); Conclusion That’s it!  I have posted a project on clrizr.codePlex.com for this, and included a testing page for you to test out how it works.  Feel free to use it in your own project, and if you have any questions, comments or suggestions, please feel free to leave them here as a comment, or on the contact page!

    Read the article

  • Redirecting to a dynamic page

    - by binarydev
    I have a page displaying blog posts (latest_posts.php) and another page that display single blog posts (blog.php) . I intend to link the image title in latest_posts.php so that it redirects to blog.php where it would display the particular post that was clicked. latest_posts.php: <!-- Header --> <h2 class="underline"> <span>What&#039;s new</span> <span></span> </h2> <!-- /Header --> <!-- Posts list --> <ul class="post-list post-list-1"> <?php /* Fetches Date/Time, Post Content and title */ include 'dbconnect.php'; $sql = "SELECT * FROM wp_posts"; $res = mysql_query($sql); while ( $row = mysql_fetch_array($res) ) { ?> <!-- Post #1 --> <li class="clear-fix"> <!-- Date --> <div class="post-list-date"> <div class="post-date-box"> <?php //Timestamp broken down to show accordingly $timestamp = $row['post_date']; $datetime = new DateTime($timestamp); $date = $datetime->format("d"); $month = $datetime->format("M"); ?> <h3> <?php echo $date; ?> </h3> <span> <?php echo $month; ?> </span> </div> </div> <!-- /Date --> <!-- Image + comments count --> <div class="post-list-image"> <!-- Image --> <div class="image image-overlay-url image-fancybox-url"> <a href="post.php" class="preloader-image"> <?php echo '<img src="', $row['image'], '" alt="' , $row['post_title'] , '\'s Blog Image" />'; ?> </a> </div> <!-- /Image --> </div> <!-- /Image + comments count --> <!-- Content --> <div class="post-list-content"> <div> <!-- Header --> <h4> <a href="post.php? . $row['ID'] . "> <?php echo $row['post_title']; ?> </a> </h4> <!-- /Header --> <!-- Excerpt --> <p> <?php echo $row ['post_content']; }?> </p> <!-- /Excerpt --> </div> </div> <!-- /Content --> </li> <!-- /Post #1 --> </ul> <!-- /Posts list --> <a href="blog.php" class="button-browse">Browse All Posts</a> </div> <?php require_once('include/twitter_user_timeline.php'); ?> blog.php: <?php require_once('include/header.php'); ?> <body class="blog"> <?php require_once('include/navigation_bar_blog.php'); ?> <div class="blog"> <div class="main"> <!-- Header --> <h2 class="underline"> <span>What&#039;s new</span> <span></span> </h2> <!-- /Header --> <!-- Layout 66x33 --> <div class="layout-p-66x33 clear-fix"> <!-- Left column --> <!-- <div class="column-left"> --> <!-- Posts list --> <ul class="post-list post-list-2"> <?php /* Fetches Date/Time, Post Content and title with Pagination */ include 'dbconnect.php'; //sets to default page if(empty($_GET['pn'])){ $page=1; } else { $page = $_GET['pn']; } // Index of the page $index = ($page-1)*3; $sql = "SELECT * FROM `wp_posts` ORDER BY `post_date` DESC LIMIT " . $index . " ,3"; $res = mysql_query($sql); //Loops through the values while ( $row = mysql_fetch_array($res) ) { ?> <!-- Post #1 --> <li class="clear-fix"> <!-- Date --> <div class="post-list-date"> <div class="post-date-box"> <?php //Timestamp broken down to show accordingly $timestamp = $row['post_date']; $datetime = new DateTime($timestamp); $date = $datetime->format("d"); $month = $datetime->format("M"); ?> <h3> <?php echo $date; ?> </h3> <span> <?php echo $month; ?> </span> </div> </div> <!-- /Date --> <!-- Image + comments count --> <div class="post-list-image"> <!-- Image --> <div class="image image-overlay-url image-fancybox-url"> <a href="post.php" class="preloader-image"> <?php echo '<img src="', $row['image'], '" alt="' , $row['post_title'] , '\'s Blog Image" />'; ?> </a> </div> <!-- /Image --> </div> <!-- /Image + comments count --> <!-- Content --> <div class="post-list-content"> <div> <?php $id = $_GET['ID']; $post = lookup_post_somehow($id); if($post) { // render post } else { echo 'blog post not found..'; } ?> <!-- Header --> <h4> <a href="post.php"> <?php echo $row['post_title']; ?> </a> </h4> <!-- /Header --> <!-- Excerpt --> <p> <?php echo $row ['post_content']; ?> </p> <!-- /Excerpt --> </div> </div> <!-- /Content --> </li> <!-- /Post #1 --> <?php } // close while loop ?> </ul> <!-- /Posts list --> <div><!-- Pagination --> <ul class="blog-pagination clear-fix"> <?php //Count the number of rows $numberofrows = mysql_query("SELECT COUNT(ID) FROM `wp_posts`"); //Do ciel() to round the result according to number of posts $postsperpage = 4; $numOfPages = ceil($numberofrows / $postsperpage); for($i=1; $i < $numOfPages; $i++) { //echos links for each page $paginationDisplay = '<li><a href="blog.php?pn=' . $i . '">' . $i . '</a></li>'; echo $paginationDisplay; } ?> <!-- <li><a href="#" class="selected">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> --> </ul> </div><!-- /Pagination --> <!-- /div> --> <!-- Left column --> </div> <!-- /Layout 66x33 --> </div> </div> <?php require_once('include/twitter_user_timeline.php'); ?> <?php require_once('include/footer_blog.php'); ?> How do I render?

    Read the article

  • Reversing page navigation on PHP

    - by ilnur777
    Can anyone help me with reversing this PHP page navigation? Current script setting shows this format: [0] | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 ... 14 • Forward • End But I really need it to reverse for this format: [14] | 13 | 12 | 11| 10 | 9 | 8 | 7 | 6 ... 0 • Back • Start Here is the PHP code: <? $onpage = 10; // on page function page(){ if(empty($_GET["page"])){ $page = 0; } else { if(!is_numeric($_GET["page"])) die("Bad page number!"); $page = $_GET["page"]; } return $page; } function navigation($onpage, $page){ //---------------- $countt = 150; $cnt=$countt; // total amount of entries $rpp=$onpage; // total entries per page $rad=4; // amount of links to show near current page (2 left + 2 right + current page = total 5) $links=$rad*2+1; $pages=ceil($cnt/$rpp); if ($page>0) { echo "<a href=\"?page=0\"><<< Start</a> <font color='#CCCCCC'>•</font> <a href=\"?page=".($page-1)."\">< Back</a> <font color='#CCCCCC'>•</font>"; } $start=$page-$rad; if ($start>$pages-$links) { $start=$pages-$links; } if ($start<0) { $start=0; } $end=$start+$links; if ($end>$pages) { $end=$pages; } for ($i=$start; $i<$end; $i++) { echo " "; if ($i==$page) { echo "["; } else { echo "<a href=\"?page=$i\">"; } echo $i; if ($i==$page) { echo "]"; } else { echo "</a>"; } if ($i!=($end-1)) { echo " <font color='#CCCCCC'>|</font>"; } } if ($pages>$links&&$page<($pages-$rad-1)) { echo " ... <a href=\"?page=".($pages-1)."\">".($pages-1)."</a>"; } if ($page<$pages-1) { echo " <font color='#CCCCCC'>•</font> <a href=\"?page=".($page+1)."\">Forward ></a> <font color='#CCCCCC'>•</font> <a href=\"?page=".($pages-1)."\">End >>></a>"; } } $page = page(); // detect page $navigation = navigation($onpage, $page); // detect navigation ?>

    Read the article

< Previous Page | 1 2 3 4 5 6  | Next Page >