Search Results

Search found 541 results on 22 pages for 'settimeout'.

Page 13/22 | < Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >

  • Firefox running infinitely even after condition met in jquery function

    - by Kyle
    The following function is called with setTimeout(function () { get_progress(fileID,fileName)},8000); upon a form submit. The purpose of the function is to get read_file.php to read a txt file that stores the file upload status from a form (in percentage). Upon reaching 80%, my Firefox seems to run infinitely even when HEAD returns an error. Am I have too many recursions or have I used a wrong condition that's causing get_progress to run repeatedly even when filename does not exist in the folder ? function get_progress( fileID, filename) { $.ajax({ url: filename, type: 'HEAD', success: function() { $.ajax({ type: 'POST', url: 'read_file.php', data: 'filename=' +filename, success: function(html) { document.getElementById(fileID).innerHTML = html + ' <img src="images/loading.gif" />' setInterval(function() {get_progress(fileID,filename)},4000); } }); } });}

    Read the article

  • Passing javascript to a function

    - by AJ
    Hello, Can I pass some Javascript to a function and then execute that Javascript from within the function, e.g. test("a = 1; b = 2; test2(a,b);"); function test(js) { // execute dynamically generated JS here. } Basically I have some code that is generated on the server and I want to pass that code to a JS function which when it has finished processing it executes the code passed as a parameter. This could also be useful for the parameter of setTimeout, then the code passed could be executed in the timeout event. Can this be done?

    Read the article

  • JQuery .get() only passing first two data parameters in url

    - by The.Anti.9
    I have a $.get() call to a PHP page that takes 4 GET parameters. For some reason, despite giving the $.get() call all 4, it only passes the first two. When I look at the dev console in chrome, it shows the URL that gets called, and it only passes action and dbname. Heres the code: $.get('util/util.php', { action: 'start', dbname: db, url: starturl, crawldepth: depth }, function(data) { if (data == 'true') { status = 1; $('#0').append(starturl + "<ul></ul>"); $('#gobutton').hide(); $('#loading').show("slow"); while(status == 1) { setTimeout("update()",10000); } } else { show_error("Form data incomplete!"); } }); and heres the URL that I see in the developer console: http://localhost/pci/util/util.php?action=start&dbname=1hkxorr9ve1kuap2.db

    Read the article

  • Does submit() function has a callback?

    - by ecu
    Hi, I have this code: setMyCookie('name','value_1'); $('.myform').submit(); setMyCookie('name','value_2'); Problem: Webkit browsers seem to update 'MyCookie' with 'value_2' before the form gets submited, or in the exact moment it is being submited, so wrong cookie value is sent with it. I want to change cookie value to 'value_2' immediately after the form is submited so the cookie is ready for another request. The following code works fine, but I don't think using timeout() is the best solution. Maybe there is another way to solve this problem? setMyCookie('name','value_1'); $('.myform').submit(); setTimeout(function(){setMyCookie('name',value_2);},100); Thanks.

    Read the article

  • Using jQuery to POST Form Data to an ASP.NET ASMX AJAX Web Service

    - by Rick Strahl
    The other day I got a question about how to call an ASP.NET ASMX Web Service or PageMethods with the POST data from a Web Form (or any HTML form for that matter). The idea is that you should be able to call an endpoint URL, send it regular urlencoded POST data and then use Request.Form[] to retrieve the posted data as needed. My first reaction was that you can’t do it, because ASP.NET ASMX AJAX services (as well as Page Methods and WCF REST AJAX Services) require that the content POSTed to the server is posted as JSON and sent with an application/json or application/x-javascript content type. IOW, you can’t directly call an ASP.NET AJAX service with regular urlencoded data. Note that there are other ways to accomplish this. You can use ASP.NET MVC and a custom route, an HTTP Handler or separate ASPX page, or even a WCF REST service that’s configured to use non-JSON inputs. However if you want to use an ASP.NET AJAX service (or Page Methods) with a little bit of setup work it’s actually quite easy to capture all the form variables on the client and ship them up to the server. The basic steps needed to make this happen are: Capture form variables into an array on the client with jQuery’s .serializeArray() function Use $.ajax() or my ServiceProxy class to make an AJAX call to the server to send this array On the server create a custom type that matches the .serializeArray() name/value structure Create extension methods on NameValue[] to easily extract form variables Create a [WebMethod] that accepts this name/value type as an array (NameValue[]) This seems like a lot of work but realize that steps 3 and 4 are a one time setup step that can be reused in your entire site or multiple applications. Let’s look at a short example that looks like this as a base form of fields to ship to the server: The HTML for this form looks something like this: <div id="divMessage" class="errordisplay" style="display: none"> </div> <div> <div class="label">Name:</div> <div><asp:TextBox runat="server" ID="txtName" /></div> </div> <div> <div class="label">Company:</div> <div><asp:TextBox runat="server" ID="txtCompany"/></div> </div> <div> <div class="label" ></div> <div> <asp:DropDownList runat="server" ID="lstAttending"> <asp:ListItem Text="Attending" Value="Attending"/> <asp:ListItem Text="Not Attending" Value="NotAttending" /> <asp:ListItem Text="Maybe Attending" Value="MaybeAttending" /> <asp:ListItem Text="Not Sure Yet" Value="NotSureYet" /> </asp:DropDownList> </div> </div> <div> <div class="label">Special Needs:<br /> <small>(check all that apply)</small></div> <div> <asp:ListBox runat="server" ID="lstSpecialNeeds" SelectionMode="Multiple"> <asp:ListItem Text="Vegitarian" Value="Vegitarian" /> <asp:ListItem Text="Vegan" Value="Vegan" /> <asp:ListItem Text="Kosher" Value="Kosher" /> <asp:ListItem Text="Special Access" Value="SpecialAccess" /> <asp:ListItem Text="No Binder" Value="NoBinder" /> </asp:ListBox> </div> </div> <div> <div class="label"></div> <div> <asp:CheckBox ID="chkAdditionalGuests" Text="Additional Guests" runat="server" /> </div> </div> <hr /> <input type="button" id="btnSubmit" value="Send Registration" /> The form includes a few different kinds of form fields including a multi-selection listbox to demonstrate retrieving multiple values. Setting up the Server Side [WebMethod] The [WebMethod] on the server we’re going to call is going to be very simple and just capture the content of these values and echo then back as a formatted HTML string. Obviously this is overly simplistic but it serves to demonstrate the simple point of capturing the POST data on the server in an AJAX callback. public class PageMethodsService : System.Web.Services.WebService { [WebMethod] public string SendRegistration(NameValue[] formVars) { StringBuilder sb = new StringBuilder(); sb.AppendFormat("Thank you {0}, <br/><br/>", HttpUtility.HtmlEncode(formVars.Form("txtName"))); sb.AppendLine("You've entered the following: <hr/>"); foreach (NameValue nv in formVars) { // strip out ASP.NET form vars like _ViewState/_EventValidation if (!nv.name.StartsWith("__")) { if (nv.name.StartsWith("txt") || nv.name.StartsWith("lst") || nv.name.StartsWith("chk")) sb.Append(nv.name.Substring(3)); else sb.Append(nv.name); sb.AppendLine(": " + HttpUtility.HtmlEncode(nv.value) + "<br/>"); } } sb.AppendLine("<hr/>"); string[] needs = formVars.FormMultiple("lstSpecialNeeds"); if (needs == null) sb.AppendLine("No Special Needs"); else { sb.AppendLine("Special Needs: <br/>"); foreach (string need in needs) { sb.AppendLine("&nbsp;&nbsp;" + need + "<br/>"); } } return sb.ToString(); } } The key feature of this method is that it receives a custom type called NameValue[] which is an array of NameValue objects that map the structure that the jQuery .serializeArray() function generates. There are two custom types involved in this: The actual NameValue type and a NameValueExtensions class that defines a couple of extension methods for the NameValue[] array type to allow for single (.Form()) and multiple (.FormMultiple()) value retrieval by name. The NameValue class is as simple as this and simply maps the structure of the array elements of .serializeArray(): public class NameValue { public string name { get; set; } public string value { get; set; } } The extension method class defines the .Form() and .FormMultiple() methods to allow easy retrieval of form variables from the returned array: /// <summary> /// Simple NameValue class that maps name and value /// properties that can be used with jQuery's /// $.serializeArray() function and JSON requests /// </summary> public static class NameValueExtensionMethods { /// <summary> /// Retrieves a single form variable from the list of /// form variables stored /// </summary> /// <param name="formVars"></param> /// <param name="name">formvar to retrieve</param> /// <returns>value or string.Empty if not found</returns> public static string Form(this NameValue[] formVars, string name) { var matches = formVars.Where(nv => nv.name.ToLower() == name.ToLower()).FirstOrDefault(); if (matches != null) return matches.value; return string.Empty; } /// <summary> /// Retrieves multiple selection form variables from the list of /// form variables stored. /// </summary> /// <param name="formVars"></param> /// <param name="name">The name of the form var to retrieve</param> /// <returns>values as string[] or null if no match is found</returns> public static string[] FormMultiple(this NameValue[] formVars, string name) { var matches = formVars.Where(nv => nv.name.ToLower() == name.ToLower()).Select(nv => nv.value).ToArray(); if (matches.Length == 0) return null; return matches; } } Using these extension methods it’s easy to retrieve individual values from the array: string name = formVars.Form("txtName"); or multiple values: string[] needs = formVars.FormMultiple("lstSpecialNeeds"); if (needs != null) { // do something with matches } Using these functions in the SendRegistration method it’s easy to retrieve a few form variables directly (txtName and the multiple selections of lstSpecialNeeds) or to iterate over the whole list of values. Of course this is an overly simple example – in typical app you’d probably want to validate the input data and save it to the database and then return some sort of confirmation or possibly an updated data list back to the client. Since this is a full AJAX service callback realize that you don’t have to return simple string values – you can return any of the supported result types (which are most serializable types) including complex hierarchical objects and arrays that make sense to your client code. POSTing Form Variables from the Client to the AJAX Service To call the AJAX service method on the client is straight forward and requires only use of little native jQuery plus JSON serialization functionality. To start add jQuery and the json2.js library to your page: <script src="Scripts/jquery.min.js" type="text/javascript"></script> <script src="Scripts/json2.js" type="text/javascript"></script> json2.js can be found here (be sure to remove the first line from the file): http://www.json.org/json2.js It’s required to handle JSON serialization for those browsers that don’t support it natively. With those script references in the document let’s hookup the button click handler and call the service: $(document).ready(function () { $("#btnSubmit").click(sendRegistration); }); function sendRegistration() { var arForm = $("#form1").serializeArray(); $.ajax({ url: "PageMethodsService.asmx/SendRegistration", type: "POST", contentType: "application/json", data: JSON.stringify({ formVars: arForm }), dataType: "json", success: function (result) { var jEl = $("#divMessage"); jEl.html(result.d).fadeIn(1000); setTimeout(function () { jEl.fadeOut(1000) }, 5000); }, error: function (xhr, status) { alert("An error occurred: " + status); } }); } The key feature in this code is the $("#form1").serializeArray();  call which serializes all the form fields of form1 into an array. Each form var is represented as an object with a name/value property. This array is then serialized into JSON with: JSON.stringify({ formVars: arForm }) The format for the parameter list in AJAX service calls is an object with one property for each parameter of the method. In this case its a single parameter called formVars and we’re assigning the array of form variables to it. The URL to call on the server is the name of the Service (or ASPX Page for Page Methods) plus the name of the method to call. On return the success callback receives the result from the AJAX callback which in this case is the formatted string which is simply assigned to an element in the form and displayed. Remember the result type is whatever the method returns – it doesn’t have to be a string. Note that ASP.NET AJAX and WCF REST return JSON data as a wrapped object so the result has a ‘d’ property that holds the actual response: jEl.html(result.d).fadeIn(1000); Slightly simpler: Using ServiceProxy.js If you want things slightly cleaner you can use the ServiceProxy.js class I’ve mentioned here before. The ServiceProxy class handles a few things for calling ASP.NET and WCF services more cleanly: Automatic JSON encoding Automatic fix up of ‘d’ wrapper property Automatic Date conversion on the client Simplified error handling Reusable and abstracted To add the service proxy add: <script src="Scripts/ServiceProxy.js" type="text/javascript"></script> and then change the code to this slightly simpler version: <script type="text/javascript"> proxy = new ServiceProxy("PageMethodsService.asmx/"); $(document).ready(function () { $("#btnSubmit").click(sendRegistration); }); function sendRegistration() { var arForm = $("#form1").serializeArray(); proxy.invoke("SendRegistration", { formVars: arForm }, function (result) { var jEl = $("#divMessage"); jEl.html(result).fadeIn(1000); setTimeout(function () { jEl.fadeOut(1000) }, 5000); }, function (error) { alert(error.message); } ); } The code is not very different but it makes the call as simple as specifying the method to call, the parameters to pass and the actions to take on success and error. No more remembering which content type and data types to use and manually serializing to JSON. This code also removes the “d” property processing in the response and provides more consistent error handling in that the call always returns an error object regardless of a server error or a communication error unlike the native $.ajax() call. Either approach works and both are pretty easy. The ServiceProxy really pays off if you use lots of service calls and especially if you need to deal with date values returned from the server  on the client. Summary Making Web Service calls and getting POST data to the server is not always the best option – ASP.NET and WCF AJAX services are meant to work with data in objects. However, in some situations it’s simply easier to POST all the captured form data to the server instead of mapping all properties from the input fields to some sort of message object first. For this approach the above POST mechanism is useful as it puts the parsing of the data on the server and leaves the client code lean and mean. It’s even easy to build a custom model binder on the server that can map the array values to properties on an object generically with some relatively simple Reflection code and without having to manually map form vars to properties and do string conversions. Keep in mind though that other approaches also abound. ASP.NET MVC makes it pretty easy to create custom routes to data and the built in model binder makes it very easy to deal with inbound form POST data in its original urlencoded format. The West Wind West Wind Web Toolkit also includes functionality for AJAX callbacks using plain POST values. All that’s needed is a Method parameter to query/form value to specify the method to be called on the server. After that the content type is completely optional and up to the consumer. It’d be nice if the ASP.NET AJAX Service and WCF AJAX Services weren’t so tightly bound to the content type so that you could more easily create open access service endpoints that can take advantage of urlencoded data that is everywhere in existing pages. It would make it much easier to create basic REST endpoints without complicated service configuration. Ah one can dream! In the meantime I hope this article has given you some ideas on how you can transfer POST data from the client to the server using JSON – it might be useful in other scenarios beyond ASP.NET AJAX services as well. Additional Resources ServiceProxy.js A small JavaScript library that wraps $.ajax() to call ASP.NET AJAX and WCF AJAX Services. Includes date parsing extensions to the JSON object, a global dataFilter for processing dates on all jQuery JSON requests, provides cleanup for the .NET wrapped message format and handles errors in a consistent fashion. Making jQuery Calls to WCF/ASMX with a ServiceProxy Client More information on calling ASMX and WCF AJAX services with jQuery and some more background on ServiceProxy.js. Note the implementation has slightly changed since the article was written. ww.jquery.js The West Wind West Wind Web Toolkit also includes ServiceProxy.js in the West Wind jQuery extension library. This version is slightly different and includes embedded json encoding/decoding based on json2.js.© Rick Strahl, West Wind Technologies, 2005-2010Posted in jQuery  ASP.NET  AJAX  

    Read the article

  • jQuery Time Entry with Time Navigation Keys

    - by Rick Strahl
    So, how do you display time values in your Web applications? Displaying date AND time values in applications is lot less standardized than date display only. While date input has become fairly universal with various date picker controls available, time entry continues to be a bit of a non-standardized. In my own applications I tend to use the jQuery UI DatePicker control for date entries and it works well for that. Here's an example: The date entry portion is well defined and it makes perfect sense to have a calendar pop up so you can pick a date from a rich UI when necessary. However, time values are much less obvious when it comes to displaying a UI or even just making time entries more useful. There are a slew of time picker controls available but other than adding some visual glitz, they are not really making time entry any easier. Part of the reason for this is that time entry is usually pretty simple. Clicking on a dropdown of any sort and selecting a value from a long scrolling list tends to take more user interaction than just typing 5 characters (7 if am/pm is used). Keystrokes can make Time Entry easier Time entry maybe pretty simple, but I find that adding a few hotkeys to handle date navigation can make it much easier. Specifically it'd be nice to have keys to: Jump to the current time (Now) Increase/decrease minutes Increase/decrease hours The timeKeys jQuery PlugIn Some time ago I created a small plugin to handle this scenario. It's non-visual other than tooltip that pops up when you press ? to display the hotkeys that are available: Try it Online The keys loosely follow the ancient Quicken convention of using the first and last letters of what you're increasing decreasing (ie. H to decrease, R to increase hours and + and - for the base unit or minutes here). All navigation happens via the keystrokes shown above, so it's all non-visual, which I think is the most efficient way to deal with dates. To hook up the plug-in, start with the textbox:<input type="text" id="txtTime" name="txtTime" value="12:05 pm" title="press ? for time options" /> Note the title which might be useful to alert people using the field that additional functionality is available. To hook up the plugin code is as simple as:$("#txtTime").timeKeys(); You essentially tie the plugin to any text box control. OptionsThe syntax for timeKeys allows for an options map parameter:$(selector).timeKeys(options); Options are passed as a parameter map object which can have the following properties: timeFormatYou can pass in a format string that allows you to format the date. The default is "hh:mm t" which is US time format that shows a 12 hour clock with am/pm. Alternately you can pass in "HH:mm" which uses 24 hour time. HH, hh, mm and t are translated in the format string - you can arrange the format as you see fit. callbackYou can also specify a callback function that is called when the date value has been set. This allows you to either re-format the date or perform post processing (such as displaying highlight if it's after a certain hour for example). Here's another example that uses both options:$("#txtTime").timeKeys({ timeFormat: "HH:mm", callback: function (time) { showStatus("new time is: " + time.toString() + " " + $(this).val() ); } }); The plugin code itself is fairly simple. It hooks the keydown event and checks for the various keys that affect time navigation which is straight forward. The bulk of the code however deals with parsing the time value and formatting the output using a Time class that implements parsing, formatting and time navigation methods. Here's the code for the timeKeys jQuery plug-in:/// <reference path="jquery.js" /> /// <reference path="ww.jquery.js" /> (function ($) { $.fn.timeKeys = function (options) { /// <summary> /// Attaches a set of hotkeys to time fields /// + Add minute - subtract minute /// H Subtract Hour R Add houR /// ? Show keys /// </summary> /// <param name="options" type="object"> /// Options: /// timeFormat: "hh:mm t" by default HH:mm alternate /// callback: callback handler after time assignment /// </param> /// <example> /// var proxy = new ServiceProxy("JsonStockService.svc/"); /// proxy.invoke("GetStockQuote",{symbol:"msft"},function(quote) { alert(result.LastPrice); },onPageError); ///</example> if (this.length < 1) return this; var opt = { timeFormat: "hh:mm t", callback: null } $.extend(opt, options); return this.keydown(function (e) { var $el = $(this); var time = new Time($el.val()); //alert($(this).val() + " " + time.toString() + " " + time.date.toString()); switch (e.keyCode) { case 78: // [N]ow time = new Time(new Date()); break; case 109: case 189: // - time.addMinutes(-1); break; case 107: case 187: // + time.addMinutes(1); break; case 72: //H time.addHours(-1); break; case 82: //R time.addHours(1); break; case 191: // ? if (e.shiftKey) $(this).tooltip("<b>N</b> Now<br/><b>+</b> add minute<br /><b>-</b> subtract minute<br /><b>H</b> Subtract Hour<br /><b>R</b> add hour", 4000, { isHtml: true }); return false; default: return true; } $el.val(time.toString(opt.timeFormat)); if (opt.callback) { // call async and set context in this element setTimeout(function () { opt.callback.call($el.get(0), time) }, 1); } return false; }); } Time = function (time, format) { /// <summary> /// Time object that can parse and format /// a time values. /// </summary> /// <param name="time" type="object"> /// A time value as a string (12:15pm or 23:01), a Date object /// or time value. /// /// </param> /// <param name="format" type="string"> /// Time format string: /// HH:mm (23:01) /// hh:mm t (11:01 pm) /// </param> /// <example> /// var time = new Time( new Date()); /// time.addHours(5); /// time.addMinutes(10); /// var s = time.toString(); /// /// var time2 = new Time(s); // parse with constructor /// var t = time2.parse("10:15 pm"); // parse with .parse() method /// alert( t.hours + " " + t.mins + " " + t.ampm + " " + t.hours25) ///</example> var _I = this; this.date = new Date(); this.timeFormat = "hh:mm t"; if (format) this.timeFormat = format; this.parse = function (time) { /// <summary> /// Parses time value from a Date object, or string in format of: /// 12:12pm or 23:01 /// </summary> /// <param name="time" type="any"> /// A time value as a string (12:15pm or 23:01), a Date object /// or time value. /// /// </param> if (!time) return null; // Date if (time.getDate) { var t = {}; var d = time; t.hours24 = d.getHours(); t.mins = d.getMinutes(); t.ampm = "am"; if (t.hours24 > 11) { t.ampm = "pm"; if (t.hours24 > 12) t.hours = t.hours24 - 12; } time = t; } if (typeof (time) == "string") { var parts = time.split(":"); if (parts < 2) return null; var time = {}; time.hours = parts[0] * 1; time.hours24 = time.hours; time.mins = parts[1].toLowerCase(); if (time.mins.indexOf("am") > -1) { time.ampm = "am"; time.mins = time.mins.replace("am", ""); if (time.hours == 12) time.hours24 = 0; } else if (time.mins.indexOf("pm") > -1) { time.ampm = "pm"; time.mins = time.mins.replace("pm", ""); if (time.hours < 12) time.hours24 = time.hours + 12; } time.mins = time.mins * 1; } _I.date.setMinutes(time.mins); _I.date.setHours(time.hours24); return time; }; this.addMinutes = function (mins) { /// <summary> /// adds minutes to the internally stored time value. /// </summary> /// <param name="mins" type="number"> /// number of minutes to add to the date /// </param> _I.date.setMinutes(_I.date.getMinutes() + mins); } this.addHours = function (hours) { /// <summary> /// adds hours the internally stored time value. /// </summary> /// <param name="hours" type="number"> /// number of hours to add to the date /// </param> _I.date.setHours(_I.date.getHours() + hours); } this.getTime = function () { /// <summary> /// returns a time structure from the currently /// stored time value. /// Properties: hours, hours24, mins, ampm /// </summary> return new Time(new Date()); h } this.toString = function (format) { /// <summary> /// returns a short time string for the internal date /// formats: 12:12 pm or 23:12 /// </summary> /// <param name="format" type="string"> /// optional format string for date /// HH:mm, hh:mm t /// </param> if (!format) format = _I.timeFormat; var hours = _I.date.getHours(); if (format.indexOf("t") > -1) { if (hours > 11) format = format.replace("t", "pm") else format = format.replace("t", "am") } if (format.indexOf("HH") > -1) format = format.replace("HH", hours.toString().padL(2, "0")); if (format.indexOf("hh") > -1) { if (hours > 12) hours -= 12; if (hours == 0) hours = 12; format = format.replace("hh", hours.toString().padL(2, "0")); } if (format.indexOf("mm") > -1) format = format.replace("mm", _I.date.getMinutes().toString().padL(2, "0")); return format; } // construction if (time) this.time = this.parse(time); } String.prototype.padL = function (width, pad) { if (!width || width < 1) return this; if (!pad) pad = " "; var length = width - this.length if (length < 1) return this.substr(0, width); return (String.repeat(pad, length) + this).substr(0, width); } String.repeat = function (chr, count) { var str = ""; for (var x = 0; x < count; x++) { str += chr }; return str; } })(jQuery); The plugin consists of the actual plugin and the Time class which handles parsing and formatting of the time value via the .parse() and .toString() methods. Code like this always ends up taking up more effort than the actual logic unfortunately. There are libraries out there that can handle this like datejs or even ww.jquery.js (which is what I use) but to keep the code self contained for this post the plugin doesn't rely on external code. There's one optional exception: The code as is has one dependency on ww.jquery.js  for the tooltip plugin that provides the small popup for all the hotkeys available. You can replace that code with some other mechanism to display hotkeys or simply remove it since that behavior is optional. While we're at it: A jQuery dateKeys plugIn Although date entry tends to be much better served with drop down calendars to pick dates from, often it's also easier to pick dates using a few simple hotkeys. Navigation that uses + - for days and M and H for MontH navigation, Y and R for YeaR navigation are a quick way to enter dates without having to resort to using a mouse and clicking around to what you want to find. Note that this plugin does have a dependency on ww.jquery.js for the date formatting functionality.$.fn.dateKeys = function (options) { /// <summary> /// Attaches a set of hotkeys to date 'fields' /// + Add day - subtract day /// M Subtract Month H Add montH /// Y Subtract Year R Add yeaR /// ? Show keys /// </summary> /// <param name="options" type="object"> /// Options: /// dateFormat: "MM/dd/yyyy" by default "MMM dd, yyyy /// callback: callback handler after date assignment /// </param> /// <example> /// var proxy = new ServiceProxy("JsonStockService.svc/"); /// proxy.invoke("GetStockQuote",{symbol:"msft"},function(quote) { alert(result.LastPrice); },onPageError); ///</example> if (this.length < 1) return this; var opt = { dateFormat: "MM/dd/yyyy", callback: null }; $.extend(opt, options); return this.keydown(function (e) { var $el = $(this); var d = new Date($el.val()); if (!d) d = new Date(1900, 0, 1, 1, 1); var month = d.getMonth(); var year = d.getFullYear(); var day = d.getDate(); switch (e.keyCode) { case 84: // [T]oday d = new Date(); break; case 109: case 189: d = new Date(year, month, day - 1); break; case 107: case 187: d = new Date(year, month, day + 1); break; case 77: //M d = new Date(year, month - 1, day); break; case 72: //H d = new Date(year, month + 1, day); break; case 191: // ? if (e.shiftKey) $el.tooltip("<b>T</b> Today<br/><b>+</b> add day<br /><b>-</b> subtract day<br /><b>M</b> subtract Month<br /><b>H</b> add montH<br/><b>Y</b> subtract Year<br/><b>R</b> add yeaR", 5000, { isHtml: true }); return false; default: return true; } $el.val(d.formatDate(opt.dateFormat)); if (opt.callback) // call async setTimeout(function () { opt.callback.call($el.get(0),d); }, 10); return false; }); } The logic for this plugin is similar to the timeKeys plugin, but it's a little simpler as it tries to directly parse the date value from a string via new Date(inputString). As mentioned it also uses a helper function from ww.jquery.js to format dates which removes the logic to perform date formatting manually which again reduces the size of the code. And the Key is… I've been using both of these plugins in combination with the jQuery UI datepicker for datetime values and I've found that I rarely actually pop up the date picker any more. It's just so much more efficient to use the hotkeys to navigate dates. It's still nice to have the picker around though - it provides the expected behavior for date entry. For time values however I can't justify the UI overhead of a picker that doesn't make it any easier to pick a time. Most people know how to type in a time value and if they want shortcuts keystrokes easily beat out any pop up UI. Hopefully you'll find this as useful as I have found it for my code. Resources Online Sample Download Sample Project © Rick Strahl, West Wind Technologies, 2005-2011Posted in jQuery  HTML   Tweet (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • HTML5/JS - Choppy Game Loop

    - by Rikonator
    I have been experimenting with HTML5/JS, trying to create a simple game when I hit a wall. My choice of game loop is too choppy to be actually of any use in a game. I'm trying for a fixed time step loop, rendering only when required. I simply use a requestAnimationFrame to run Game.update which finds the elapsed time since the last update, and calls State.update to update and render the current state. State.prototype.update = function(ms) { this.ticks += ms; var updates = 0; while(this.ticks >= State.DELTA_TIME && updates < State.MAX_UPDATES) { this.updateState(); this.updateFrameTicks += State.DELTA_TIME; this.updateFrames++; if(this.updateFrameTicks >= 1000) { this.ups = this.updateFrames; this.updateFrames = 0; this.updateFrameTicks -= 1000; } this.ticks -= State.DELTA_TIME; updates++; } if(updates > 0) { this.renderFrameTicks += updates*State.DELTA_TIME; this.renderFrames++; if(this.renderFrameTicks >= 1000) { this.rps = this.renderFrames; this.renderFrames = 0; this.renderFrameTicks -= 1000; } this.renderState(updates*State.DELTA_TIME); } }; But this strategy does not work very well. This is the result: http://jsbin.com/ukosuc/1 (Edit). As it is apparent, the 'game' has fits of lag, and when you tab out for a long period and come back, the 'game' behaves unexpectedly - updates faster than intended. This is either a problem due to something about game loops that I don't quite understand yet, or a problem due to implementation which I can't pinpoint. I haven't been able to solve this problem despite attempting several variations using setTimeout and requestAnimationFrame. (One such example is http://jsbin.com/eyarod/1/edit). Some help and insight would really be appreciated!

    Read the article

  • How to implement line of sight restriction in actionscript?

    - by Michiel Standaert
    I have a problem with a game i am programming. I am making some sort of security game and i would like to have some visual line of sight. The problem is that i can't restrict my line of sight so my cops can't see through the walls. Below you find the design, in which they can look through windows, but not walls. Further below you find an illustration of what my problem is exactly. this is what it looks like now. As you can see, the cops can see through walls. This is the map i would want to use to restrict the line of sight. So the way i am programming the line of sight now is just by calculating some points and drawing the sight accordingly, as shown below. Note that i also check for a hittest using bitmapdata to check whether or not my player has been spotted by any of the cops. private function setSight(e:Event=null):Boolean { g = copCanvas.graphics; g.clear(); for each(var cop:Cop in copCanvas.getChildren()) { var _angle:Number = cop.angle; var _radians:Number = (_angle * Math.PI) / 180; var _radius:Number = 50; var _x1:Number = cop.x + (cop.width/2); var _y1:Number = cop.y + (cop.height/2); var _baseX:Number = _x1 + (Math.cos(_radians) * _radius); var _baseY:Number = _y1 - (Math.sin(_radians) * _radius); var _x2:Number = _baseX + (25 * Math.sin(_radians)); var _y2:Number = _baseY + (25 * Math.cos(_radians)); var _x3:Number = _baseX - (25 * Math.sin(_radians)); var _y3:Number = _baseY - (25 * Math.cos(_radians)); g.beginFill(0xff0000, 0.3); g.moveTo(_x1, _y1); g.lineTo(_x2, _y2); g.lineTo(_x3, _y3); g.endFill(); } var _cops:BitmapData = new BitmapData(width, height, true, 0); _cops.draw(copCanvas); var _bmpd:BitmapData = new BitmapData(10, 10, true, 0); _bmpd.draw(me); if(_cops.hitTest(new Point(0, 0), 10, _bmpd, new Point(me.x, me.y), 255)) { gameover.alpha = 1; setTimeout(function():void{ gameover.alpha = 0; }, 5000); stop(); return true; } return false; } So now my question is: Is there someone who knows how to restrict the view so that the cops can't look through the walls? Thanks a lot in advance. ps: i have already looked at this tutorial by emanuele feronato, but i can't use the code to restric the visual line of sight.

    Read the article

  • Slow Firefox Javascript Canvas Performance?

    - by jujumbura
    As a followup from a previous post, I have been trying to track down some slowdown I am having when drawing a scene using Javascript and the canvas element. I decided to narrow down my focus to a REALLY barebones animation that only clears the canvas and draws a single image, once per-frame. This of course runs silky smooth in Chrome, but it still stutters in Firefox. I added a simple FPS calculator, and indeed it appears that my page is typically getting an FPS in the 50's when running Firefox. This doesn't seem right to me, I must be doing something wrong here. Can anybody see anything I might be doing that is causing this drop in FPS? <!DOCTYPE HTML> <html> <head> </head> <body bgcolor=silver> <canvas id="myCanvas" width="600" height="400"></canvas> <img id="myHexagon" src="Images/Hexagon.png" style="display: none;"> <script> window.requestAnimFrame = (function(callback) { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60); }; })(); var animX = 0; var frameCounter = 0; var fps = 0; var time = new Date(); function animate() { var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); context.clearRect(0, 0, canvas.width, canvas.height); animX += 1; if (animX == canvas.width) { animX = 0; } var image = document.getElementById("myHexagon"); context.drawImage(image, animX, 128); context.lineWidth=1; context.fillStyle="#000000"; context.lineStyle="#ffffff"; context.font="18px sans-serif"; context.fillText("fps: " + fps, 20, 20); ++frameCounter; var currentTime = new Date(); var elapsedTimeMS = currentTime - time; if (elapsedTimeMS >= 1000) { fps = frameCounter; frameCounter = 0; time = currentTime; } // request new frame requestAnimFrame(function() { animate(); }); } window.onload = function() { animate(); }; </script> </body> </html>

    Read the article

  • Antenna Aligner Part 5: Devil is in the detail

    - by Chris George
    "The first 90% of a project takes 90% of the time and the last 10% takes the another 200%"  (excerpt from onista) Now that I have a working app (more or less), it's time to make it pretty and slick. I can't stress enough how useful it is to get other people using your software, and my simple app is no exception. I handed my iPhone to a couple of my colleagues at Red Gate and asked them to use it and give me feedback. Immediately it became apparent that the delay between the list page being shown and the list being drawn was too long, and everyone who tried the app clicked on the "Recalculate" button before it had finished. Similarly, selecting a transmitter heralded a delay before the compass page appeared with similar consequences. All users expected there to be some sort of feedback/spinny etc. to show them it is actually doing something. In a similar vein although for opposite reasons, clicking the Recalculate button did indeed recalculate the available transmitters and redraw them, but it did this too fast! One or two users commented that they didn't know if it had done anything. All of these issues resulted in similar solutions; implement a waiting spinny. Thankfully, jquery mobile has one built in, primarily used for ajax operations. Not wishing to bore you with the many many iterations I went through trying to get this to work, I'll just give you my solution! (Seriously, I was working on this most evenings for at least a week!) The final solution for the recalculate problem came in the form of the code below. $(document).on("click", ".show-page-loading-msg", function () {            var $this = $(this),                theme = $this.jqmData("theme") ||                        $.mobile.loadingMessageTheme;            $.mobile.showPageLoadingMsg(theme, "recalculating", false);            setTimeout(function ()                           { $.mobile.hidePageLoadingMsg(); }, 2000);            getLocationData();        })        .on("click", ".hide-page-loading-msg", function () {              $.mobile.hidePageLoadingMsg();        }); The spinny is activated by setting the class of a button (for example) to the 'show-page-loading-msg' class. Recalculate This means the code above is fired, calling the showPageLoadingMsg on the document.mobile object. Then, after a 2 second timeout, it calls the hidePageLoadingMsg() function. Supposedly, it should show "recalculating" underneath the spinny, but I've not got that to work. I'm wondering if there is a problem with the jquery mobile implementation. Anyway, it doesn't really matter, it's the principle I'm after, and I now have spinnys!

    Read the article

  • How can I clear explosions in my function?

    - by hustlerinc
    Hi I have a function to place bombs, and a for loop that places explosions on the tiles where possible. My problem is that I can't remove the explosions after a while. I've tried everything I can come up with so now I turn here as a last resort. The function looks like this: function Bomb(){ var placebomb = false; if(placeBomb && player.bombs != 0){ map[player.Y][player.X].object = 2; var bombX = player.X; var bombY = player.Y; placeBomb = false; player.bombs--; setTimeout(explode, 3000); } function explode(){ var explodeNorth = true; var explodeEast = true; var explodeSouth = true; var explodeWest = true; map[bombY][bombX].explosion = 1; delete map[bombY][bombX].object; for(i=0;i<=player.bombRadius;i++){ if(explodeNorth && map[bombY-i][bombX]){ if(!map[bombY-i][bombX].wall){ if(!map[bombY-i][bombX].object){ map[bombY-i][bombX].explosion = 1; } else var explodeNorth = false; delete map[bombY-i][bombX].object; map[bombY-i][bombX].explosion = 1; } else var explodeNorth = false; } if(explodeEast && map[bombY][bombX+i]){ if(!map[bombY][bombX+i].wall){ if(!map[bombY][bombX+i].object){ map[bombY][bombX+i].explosion = 1; } else var explodeEast = false; delete map[bombY][bombX+i].object; map[bombY][bombX+i].explosion = 1; } else var explodeEast = false; } if(explodeSouth && map[bombY+i][bombX]){ if(!map[bombY+i][bombX].wall){ if(!map[bombY+i][bombX].object){ map[bombY+i][bombX].explosion = 1; } else var explodeSouth = false; delete map[bombY+i][bombX].object; map[bombY+i][bombX].explosion = 1; } else var explodeSouth = false; } if(explodeWest && map[bombY][bombX-i]){ if(!map[bombY][bombX-i].wall){ if(!map[bombY][bombX-i].object){ map[bombY][bombX-i].explosion = 1; } else var explodeWest = false; delete map[bombY][bombX-i].object; map[bombY][bombX-i].explosion = 1; } else var explodeWest = false; } } player.bombs++; } } If anyone can think of a good way to remove the explosion after a delay please help.

    Read the article

  • Antenna Aligner Part 5: Devil is in the detail

    - by Chris George
    "The first 90% of a project takes 90% of the time and the last 10% takes the another 200%"  (excerpt from onista) Now that I have a working app (more or less), it's time to make it pretty and slick. I can't stress enough how useful it is to get other people using your software, and my simple app is no exception. I handed my iPhone to a couple of my colleagues at Red Gate and asked them to use it and give me feedback. Immediately it became apparent that the delay between the list page being shown and the list being drawn was too long, and everyone who tried the app clicked on the "Recalculate" button before it had finished. Similarly, selecting a transmitter heralded a delay before the compass page appeared with similar consequences. All users expected there to be some sort of feedback/spinny etc. to show them it is actually doing something. In a similar vein although for opposite reasons, clicking the Recalculate button did indeed recalculate the available transmitters and redraw them, but it did this too fast! One or two users commented that they didn't know if it had done anything. All of these issues resulted in similar solutions; implement a waiting spinny. Thankfully, jquery mobile has one built in, primarily used for ajax operations. Not wishing to bore you with the many many iterations I went through trying to get this to work, I'll just give you my solution! (Seriously, I was working on this most evenings for at least a week!) The final solution for the recalculate problem came in the form of the code below. $(document).on("click", ".show-page-loading-msg", function () {            var $this = $(this),                theme = $this.jqmData("theme") ||                        $.mobile.loadingMessageTheme;            $.mobile.showPageLoadingMsg(theme, "recalculating", false);            setTimeout(function ()                           { $.mobile.hidePageLoadingMsg(); }, 2000);            getLocationData();        })        .on("click", ".hide-page-loading-msg", function () {              $.mobile.hidePageLoadingMsg();        }); The spinny is activated by setting the class of a button (for example) to the 'show-page-loading-msg' class. &lt;a data-role="button" class="show-page-loading-msg"Recalculate This means the code above is fired, calling the showPageLoadingMsg on the document.mobile object. Then, after a 2 second timeout, it calls the hidePageLoadingMsg() function. Supposedly, it should show "recalculating" underneath the spinny, but I've not got that to work. I'm wondering if there is a problem with the jquery mobile implementation. Anyway, it doesn't really matter, it's the principle I'm after, and I now have spinnys!

    Read the article

  • preview form using javascript in popup

    - by user1015309
    please I need some help in previewing a form in popup. I have a form, quite big, so I added the option of preview to show as popup. The lightbox form popup works well, but the problem I now have is function passform ()passing the inputs(textfield, select, checkbox, radio) into the popup page for preview on Click(). Below are my javascript and html codes. I left the css and some html out, because I think they're not needed. I will appreciate your help. Thank you The Javascript function gradient(id, level) { var box = document.getElementById(id); box.style.opacity = level; box.style.MozOpacity = level; box.style.KhtmlOpacity = level; box.style.filter = "alpha(opacity=" + level * 100 + ")"; box.style.display="block"; return; } function fadein(id) { var level = 0; while(level <= 1) { setTimeout( "gradient('" + id + "'," + level + ")", (level* 1000) + 10); level += 0.01; } } // Open the lightbox function openbox(formtitle, fadin) { var box = document.getElementById('box'); document.getElementById('shadowing').style.display='block'; var btitle = document.getElementById('boxtitle'); btitle.innerHTML = formtitle; if(fadin) { gradient("box", 0); fadein("box"); } else { box.style.display='block'; } } // Close the lightbox function closebox() { document.getElementById('box').style.display='none'; document.getElementById('shadowing').style.display='none'; } //pass form fields into variables var divexugsotherugsexams1 = document.getElementById('divexugsotherugsexams1'); var exugsotherugsexams1 = document.form4.exugsotherugsexams1.value; function passform() { divexugsotherugsexams1.innerHTML = document.form4.exugsotherugsexams1.value; } The HTML(with just one text field try): <p><input name="submit4" type="submit" class="button2" id="submit4" value="Preview Note" onClick="openbox('Preview Note', 1)"/> </p> <div id="shadowing"></div> <div id="box"> <span id="boxtitle"></span> <div id="divexugsotherugsexams1"></div> <script>document.write('<PARAM name="SRC" VALUE="'+exugsotherugsexams1+'">')</script> <a href="#" onClick="closebox()">Close</a> </div>

    Read the article

  • HTML5 game programming style

    - by fnx
    I am currently trying learn javascript in form of HTML5 games. Stuff that I've done so far isn't too fancy since I'm still a beginner. My biggest concern so far has been that I don't really know what is the best way to code since I don't know the pros and cons of different methods, nor I've found any good explanations about them. So far I've been using the worst (and propably easiest) method of all (I think) since I'm just starting out, for example like this: var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var width = 640; var height = 480; var player = new Player("pic.png", 100, 100, ...); also some other global vars... function Player(imgSrc, x, y, ...) { this.sprite = new Image(); this.sprite.src = imgSrc; this.x = x; this.y = y; ... } Player.prototype.update = function() { // blah blah... } Player.prototype.draw = function() { // yada yada... } function GameLoop() { player.update(); player.draw(); setTimeout(GameLoop, 1000/60); } However, I've seen a few examples on the internet that look interesting, but I don't know how to properly code in these styles, nor do I know if there are names for them. These might not be the best examples but hopefully you'll get the point: 1: Game = { variables: { width: 640, height: 480, stuff: value }, init: function(args) { // some stuff here }, update: function(args) { // some stuff here }, draw: function(args) { // some stuff here }, }; // from http://codeincomplete.com/posts/2011/5/14/javascript_pong/ 2: function Game() { this.Initialize = function () { } this.LoadContent = function () { this.GameLoop = setInterval(this.RunGameLoop, this.DrawInterval); } this.RunGameLoop = function (game) { this.Update(); this.Draw(); } this.Update = function () { // update } this.Draw = function () { // draw game frame } } // from http://www.felinesoft.com/blog/index.php/2010/09/accelerated-game-programming-with-html5-and-canvas/ 3: var engine = {}; engine.canvas = document.getElementById('canvas'); engine.ctx = engine.canvas.getContext('2d'); engine.map = {}; engine.map.draw = function() { // draw map } engine.player = {}; engine.player.draw = function() { // draw player } // from http://that-guy.net/articles/ So I guess my questions are: Which is most CPU efficient, is there any difference between these styles at runtime? Which one allows for easy expandability? Which one is the most safe, or at least harder to hack? Are there any good websites where stuff like this is explained? or... Does it all come to just personal preferance? :)

    Read the article

  • Flash IO error while uploading photo with low uploading internet speed

    - by Beck
    Actionscript: System.security.allowDomain("http://" + _root.tdomain + "/"); import flash.net.FileReferenceList; import flash.net.FileReference; import flash.external.ExternalInterface; import flash.external.*; /* Main variables */ var session_photos = _root.ph; var how_much_you_can_upload = 0; var selected_photos; // container for selected photos var inside_photo_num = 0; // for photo in_array selection var created_elements = _root.ph; var for_js_num = _root.ph; /* Functions & settings for javascript<->flash conversation */ var methodName:String = "addtoflash"; var instance:Object = null; var method:Function = addnewphotonumber; var wasSuccessful:Boolean = ExternalInterface.addCallback(methodName, instance, method); function addnewphotonumber() { session_photos--; created_elements--; for_js_num--; } /* Javascript hide and show flash button functions */ function block(){getURL("Javascript: blocking();");} function unblock(){getURL("Javascript:unblocking();");} /* Creating HTML platform function */ var result = false; /* Uploading */ function uploadthis(photos:Array) { if(!photos[inside_photo_num].upload("http://" + _root.tdomain + "/upload.php?PHPSESSID=" + _root.phpsessionid)) { getURL("Javascript:error_uploading();"); } } /* Flash button(applet) options and bindings */ var fileTypes:Array = new Array(); var imageTypes:Object = new Object(); imageTypes.description = "Images (*.jpg)"; imageTypes.extension = "*.jpg;"; fileTypes.push(imageTypes); var fileListener:Object = new Object(); var btnListener:Object = new Object(); btnListener.click = function(eventObj:Object) { var fileRef:FileReferenceList = new FileReferenceList(); fileRef.addListener(fileListener); fileRef.browse(fileTypes); } uploadButton.addEventListener("click", btnListener); /* Listeners */ fileListener.onSelect = function(fileRefList:FileReferenceList):Void { // reseting values inside_photo_num = 0; var list:Array = fileRefList.fileList; var item:FileReference; // PHP photo counter how_much_you_can_upload = 3 - session_photos; if(list.length > how_much_you_can_upload) { getURL("Javascript:howmuch=" + how_much_you_can_upload + ";list_length=" + list.length + ";limit_reached();"); return; } // if session variable isn't yet refreshed, we check inner counter if(created_elements >= 3) { getURL("Javascript:limit_reached();"); return; } selected_photos = list; for(var i:Number = 0; i < list.length; i++) { how_much_you_can_upload--; item = list[i]; trace("name: " + item.name); trace(item.addListener(this)); if((item.size / 1024) > 5000) {getURL("Javascript:size_limit_reached();");return;} } result = false; setTimeout(block,500); /* Increment number for new HTML container and pass it to javascript, after javascript returns true and we start uploading */ for_js_num++; if(ExternalInterface.call("create_platform",for_js_num)) { uploadthis(selected_photos); } } fileListener.onProgress = function(file:FileReference, bytesLoaded:Number, bytesTotal:Number):Void { getURL("Javascript:files_process(" + bytesLoaded + "," + bytesTotal + "," + for_js_num + ");"); } fileListener.onComplete = function(file:FileReference, bytesLoaded:Number, bytesTotal:Number):Void { inside_photo_num++; var sendvar_lv:LoadVars = new LoadVars(); var loadvar_lv:LoadVars = new LoadVars(); loadvar_lv.onLoad = function(success:Boolean){ if(loadvar_lv.failed == 1) { getURL("Javascript:type_failed();"); return; } getURL("Javascript:filelinks='" + loadvar_lv.json + "';fullname='" + loadvar_lv.fullname + "';completed(" + for_js_num + ");"); created_elements++; if((inside_photo_num + 1) > selected_photos.length) {setTimeout(unblock,1000);return;} // don't create empty containers anymore if(created_elements >= 3) {return;} result = false; /* Increment number for new HTML container and pass it to javascript, after javascript returns true and we start uploading */ for_js_num++; if(ExternalInterface.call("create_platform",for_js_num)) { uploadthis(selected_photos); } } sendvar_lv.getnum = true; sendvar_lv.PHPSESSID = _root.phpsessionid; sendvar_lv.sendAndLoad("http://" + _root.tdomain + "/upload.php",loadvar_lv,"POST"); } fileListener.onCancel = function(file:FileReference):Void { } fileListener.onOpen = function(file:FileReference):Void { } fileListener.onHTTPError = function(file:FileReference, httpError:Number):Void { getURL("Javascript:http_error(" + httpError + ");"); } fileListener.onSecurityError = function(file:FileReference, errorString:String):Void { getURL("Javascript:security_error(" + errorString + ");"); } fileListener.onIOError = function(file:FileReference):Void { getURL("Javascript:io_error();"); selected_photos[inside_photo_num].cancel(); uploadthis(selected_photos); } <PARAM name="allowScriptAccess" value="always"> <PARAM name="swliveconnect" value="true"> <PARAM name="movie" value="http://www.localh.com/fileref.swf?ph=0&phpsessionid=8mirsjsd75v6vk583vkus50qbb2djsp6&tdomain=www.localh.com"> <PARAM name="wmode" value="opaque"> <PARAM name="quality" value="high"> <PARAM name="bgcolor" value="#ffffff"> <EMBED swliveconnect="true" wmode="opaque" src="http://www.localh.com/fileref.swf?ph=0&phpsessionid=8mirsjsd75v6vk583vkus50qbb2djsp6&tdomain=www.localh.com" quality="high" bgcolor="#ffffff" width="100" height="22" name="fileref" align="middle" allowScriptAccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></EMBED> My uploading speed is 40kb/sec Getting flash error while uploading photos bigger than 500kb and getting no error while uploading photos less than 100-500kb~. My friend has 8mbit uploading speed and has no errors even while uploading 3.2mb photos and more. How to fix this problem? I have tried to re-upload on IO error trigger, but it stops at the same place. Any solution regarding this error? By the way, i was watching process via debugging proxy and figured out, that responce headers doesn't come at all on this IO error. And sometimes shows socket error. If need, i will post serverside php script as well. But it stops at if(isset($_FILES['Filedata'])) { so it won't help :) as all processing comes after this check.

    Read the article

  • Problem while running the j2me application

    - by Paru
    I am not able to view any content in the emulator while running the application. The Build is not failed and i am able run the application successfully. While i am closing the emulator i am getting an error. i can provide both code and log here. import javax.microedition.lcdui.; import javax.microedition.midlet.; import java.io.; import java.lang.; import javax.microedition.io.; import javax.microedition.rms.; public class Login extends MIDlet implements CommandListener { TextField ItemName=null; TextField ItemNo=null; TextField UserName=null; TextField Password=null; Form authForm,mainscreen; TextBox t = null; StringBuffer b = new StringBuffer(); private Display myDisplay = null; private Command okCommand = new Command("Login", Command.OK, 1); private Command exitCommand = new Command("Exit", Command.EXIT, 2); private Command sendCommand = new Command("Send", Command.OK, 1); private Command backCommand = new Command("Back", Command.BACK, 2); private Alert alert = null; public Login() { ItemName=new TextField("Item Name","",10,TextField.ANY); ItemNo=new TextField("Item No","",10,TextField.ANY); myDisplay = Display.getDisplay(this); UserName=new TextField("Your Name","",10,TextField.ANY); Password=new TextField("Password","",10,TextField.PASSWORD); authForm=new Form("Identification"); mainscreen=new Form("Logging IN"); mainscreen.addCommand(sendCommand); mainscreen.addCommand(backCommand); authForm.append(UserName); authForm.append(Password); authForm.addCommand(okCommand); authForm.addCommand(exitCommand); authForm.setCommandListener(this); myDisplay.setCurrent(authForm); } public void startApp() throws MIDletStateChangeException { } public void pauseApp() { } protected void destroyApp(boolean unconditional) throws MIDletStateChangeException { } public void commandAction(Command c, Displayable d) { if ((c == okCommand) && (d == authForm)) { if (UserName.getString().equals("") || Password.getString().equals("")){ alert = new Alert("Error", "You should enter Username and Password", null, AlertType.ERROR); alert.setTimeout(Alert.FOREVER); myDisplay.setCurrent(alert); } else{ //myDisplay.setCurrent(mainscreen); login(UserName.getString(),Password.getString()); } } if ((c == backCommand) && (d == mainscreen)) { myDisplay.setCurrent(authForm); } if ((c == exitCommand) && (d == authForm)) { notifyDestroyed(); } if ((c == sendCommand) && (d == mainscreen)) { if(ItemName.getString().equals("") || ItemNo.getString().equals("")){ } else{ sendItem(ItemName.getString(),ItemNo.getString()); } } } public void login(String UserName,String PassWord) { HttpConnection connection=null; DataInputStream in=null; String url="http://olario.net/submitpost/submitpost/login.php"; OutputStream out=null; try { connection=(HttpConnection)Connector.open(url); connection.setRequestMethod(HttpConnection.POST); connection.setRequestProperty("IF-Modified-Since", "2 Oct 2002 15:10:15 GMT"); connection.setRequestProperty("User-Agent","Profile/MIDP-1.0 Configuration/CLDC-1.0"); connection.setRequestProperty("Content-Language", "en-CA"); connection.setRequestProperty("Content-Length",""+ (UserName.length()+PassWord.length())); connection.setRequestProperty("username",UserName); connection.setRequestProperty("password",PassWord); out = connection.openDataOutputStream(); out.flush(); in = connection.openDataInputStream(); int ch; while((ch = in.read()) != -1) { b.append((char) ch); //System.out.println((char)ch); } //t = new TextBox("Reply",b.toString(),1024,0); //mainscreen.append(b.toString()); String auth=b.toString(); if(in!=null) in.close(); if(out!=null) out.close(); if(connection!=null) connection.close(); if(auth.equals("ok")){ mainscreen.setCommandListener(this); myDisplay.setCurrent(mainscreen); } } catch(IOException x){ } } public void sendItem(String itemname,String itemno){ HttpConnection connection=null; DataInputStream in=null; String url="http://www.olario.net/submitpost/submitpost/submitPost.php"; OutputStream out=null; try { connection=(HttpConnection)Connector.open(url); connection.setRequestMethod(HttpConnection.POST); connection.setRequestProperty("IF-Modified-Since", "2 Oct 2002 15:10:15 GMT"); connection.setRequestProperty("User-Agent","Profile/MIDP-1.0 Configuration/CLDC-1.0"); connection.setRequestProperty("Content-Language", "en-CA"); connection.setRequestProperty("Content-Length",""+ (itemname.length()+itemno.length())); connection.setRequestProperty("itemCode",itemname); connection.setRequestProperty("qty",itemno); out = connection.openDataOutputStream(); out.flush(); in = connection.openDataInputStream(); int ch; while((ch = in.read()) != -1) { b.append((char) ch); //System.out.println((char)ch); } //t = new TextBox("Reply",b.toString(),1024,0); //mainscreen.append(b.toString()); String send=b.toString(); if(in!=null) in.close(); if(out!=null) out.close(); if(connection!=null) connection.close(); if(send.equals("added")){ alert = new Alert("Error", "Send Successfully", null, AlertType.INFO); alert.setTimeout(Alert.FOREVER); myDisplay.setCurrent(alert); } } catch(IOException x){ } } } and the log is pre-init: pre-load-properties: exists.config.active: exists.netbeans.user: exists.user.properties.file: load-properties: exists.platform.active: exists.platform.configuration: exists.platform.profile: basic-init: cldc-pre-init: cldc-init: cdc-init: ricoh-pre-init: ricoh-init: semc-pre-init: semc-init: savaje-pre-init: savaje-init: sjmc-pre-init: sjmc-init: ojec-pre-init: ojec-init: cdc-hi-pre-init: cdc-hi-init: nokiaS80-pre-init: nokiaS80-init: nsicom-pre-init: nsicom-init: post-init: init: conditional-clean-init: conditional-clean: deps-jar: pre-preprocess: do-preprocess: Pre-processing 0 file(s) into /home/sreekumar/NetBeansProjects/Login/build/preprocessed directory. post-preprocess: preprocess: pre-compile: extract-libs: do-compile: post-compile: compile: pre-obfuscate: proguard-init: skip-obfuscation: proguard: post-obfuscate: obfuscate: lwuit-build: pre-preverify: do-preverify: post-preverify: preverify: pre-jar: set-password-init: set-keystore-password: set-alias-password: set-password: create-jad: add-configuration: add-profile: do-extra-libs: nokiaS80-prepare-j9: nokiaS80-prepare-manifest: nokiaS80-prepare-manifest-no-icon: nokiaS80-create-manifest: jad-jsr211-properties.check: jad-jsr211-properties: semc-build-j9: do-jar: nsicom-create-manifest: do-jar-no-manifest: update-jad: Updating application descriptor: /home/sreekumar/NetBeansProjects/Login/dist/Login.jad Generated "/home/sreekumar/NetBeansProjects/Login/dist/Login.jar" is 3501 bytes. sign-jar: ricoh-init-dalp: ricoh-add-app-icon: ricoh-build-dalp-with-icon: ricoh-build-dalp-without-icon: ricoh-build-dalp: savaje-prepare-icon: savaje-build-jnlp: post-jar: jar: pre-run: netmon.check: open-netmon: cldc-run: Copying 1 file to /home/sreekumar/NetBeansProjects/Login/dist/nbrun4244989945642509378 Copying 1 file to /home/sreekumar/NetBeansProjects/Login/dist/nbrun4244989945642509378 Jad URL for OTA execution: http://localhost:8082/servlet/org.netbeans.modules.mobility.project.jam.JAMServlet//home/sreekumar/NetBeansProjects/Login/dist//Login.jad Starting emulator in execution mode Running with storage root /home/sreekumar/j2mewtk/2.5.2/appdb/temp.DefaultColorPhone1 /home/sreekumar/NetBeansProjects/Login/nbproject/build-impl.xml:915: Execution failed with error code 143. BUILD FAILED (total time: 35 seconds)

    Read the article

  • How to connect to bluetoothbee device using j2me?

    - by user1500412
    I developed a simple bluetooth connection application in j2me. I try it on emulator, both server and client can found each other, but when I deploy the application to blackberry mobile phone and connect to a bluetoothbee device it says service search no records. What could it be possibly wrong? is it j2me can not find a service in bluetoothbee? The j2me itself succeed to found the bluetoothbee device, but why it can not find the service? My code is below. What I don't understand is the UUID? how to set UUID for unknown source? since I didn't know the UUID for the bluetoothbee device. class SearchingDevice extends Canvas implements Runnable,CommandListener,DiscoveryListener{ //...... public SearchingDevice(MenuUtama midlet, Display display){ this.display = display; this.midlet = midlet; t = new Thread(this); t.start(); timer = new Timer(); task = new TestTimerTask(); /*--------------------Device List------------------------------*/ select = new Command("Pilih",Command.OK,0); back = new Command("Kembali",Command.BACK,0); btDevice = new List("Pilih Device",Choice.IMPLICIT); btDevice.addCommand(select); btDevice.addCommand(back); btDevice.setCommandListener(this); /*------------------Input Form---------------------------------*/ formInput = new Form("Form Input"); nama = new TextField("Nama","",50,TextField.ANY); umur = new TextField("Umur","",50,TextField.ANY); measure = new Command("Ukur",Command.SCREEN,0); gender = new ChoiceGroup("Jenis Kelamin",Choice.EXCLUSIVE); formInput.addCommand(back); formInput.addCommand(measure); gender.append("Pria", null); gender.append("Wanita", null); formInput.append(nama); formInput.append(umur); formInput.append(gender); formInput.setCommandListener(this); /*---------------------------------------------------------------*/ findDevice(); } /*----------------Gambar screen searching device---------------------------------*/ protected void paint(Graphics g) { g.setColor(0,0,0); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(255,255,255); g.drawString("Mencari Device", 20, 20, Graphics.TOP|Graphics.LEFT); if(this.counter == 1){ g.setColor(255,115,200); g.fillRect(20, 100, 20, 20); } if(this.counter == 2){ g.setColor(255,115,200); g.fillRect(20, 100, 20, 20); g.setColor(100,255,255); g.fillRect(60, 80, 20, 40); } if(this.counter == 3){ g.setColor(255,115,200); g.fillRect(20, 100, 20, 20); g.setColor(100,255,255); g.fillRect(60, 80, 20, 40); g.setColor(255,115,200); g.fillRect(100, 60, 20, 60); } if(this.counter == 4){ g.setColor(255,115,200); g.fillRect(20, 100, 20, 20); g.setColor(100,255,255); g.fillRect(60, 80, 20, 40); g.setColor(255,115,200); g.fillRect(100, 60, 20, 60); g.setColor(100,255,255); g.fillRect(140, 40, 20, 80); //display.callSerially(this); } } /*--------- Running Searching Screen ----------------------------------------------*/ public void run() { while(run){ this.counter++; if(counter > 4){ this.counter = 1; } try { Thread.sleep(1000); } catch (InterruptedException ex) { System.out.println("interrupt"+ex.getMessage()); } repaint(); } } /*-----------------------------cari device bluetooth yang -------------------*/ public void findDevice(){ try { devices = new java.util.Vector(); local = LocalDevice.getLocalDevice(); agent = local.getDiscoveryAgent(); local.setDiscoverable(DiscoveryAgent.GIAC); agent.startInquiry(DiscoveryAgent.GIAC, this); } catch (BluetoothStateException ex) { System.out.println("find device"+ex.getMessage()); } } /*-----------------------------jika device ditemukan--------------------------*/ public void deviceDiscovered(RemoteDevice rd, DeviceClass dc) { devices.addElement(rd); } /*--------------Selesai tes koneksi ke bluetooth server--------------------------*/ public void inquiryCompleted(int param) { switch(param){ case DiscoveryListener.INQUIRY_COMPLETED: //inquiry completed normally if(devices.size()>0){ //at least one device has been found services = new java.util.Vector(); this.findServices((RemoteDevice)devices.elementAt(0)); this.run = false; do_alert("Inquiry completed",4000); }else{ do_alert("No device found in range",4000); } break; case DiscoveryListener.INQUIRY_ERROR: do_alert("Inquiry error",4000); break; case DiscoveryListener.INQUIRY_TERMINATED: do_alert("Inquiry canceled",4000); break; } } /*-------------------------------Cari service bluetooth server----------------------------*/ public void findServices(RemoteDevice device){ try { // int[] attributes = {0x100,0x101,0x102}; UUID[] uuids = new UUID[1]; //alamat server uuids[0] = new UUID("F0E0D0C0B0A000908070605040302010",false); //uuids[0] = new UUID("8841",true); //menyiapkan device lokal local = LocalDevice.getLocalDevice(); agent = local.getDiscoveryAgent(); //mencari service dari server agent.searchServices(null, uuids, device, this); //server = (StreamConnectionNotifies)Connector.open(url.toString()); } catch (BluetoothStateException ex) { // ex.printStackTrace(); System.out.println("Errorx"+ex.getMessage()); } } /*---------------------------Pencarian service selesai------------------------*/ public void serviceSearchCompleted(int transID, int respCode) { switch(respCode){ case DiscoveryListener.SERVICE_SEARCH_COMPLETED: if(currentDevice == devices.size() - 1){ if(services.size() > 0){ this.run = false; display.setCurrent(btDevice); do_alert("Service found",4000); }else{ do_alert("The service was not found",4000); } }else{ currentDevice++; this.findServices((RemoteDevice)devices.elementAt(currentDevice)); } break; case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE: do_alert("Device not Reachable",4000); break; case DiscoveryListener.SERVICE_SEARCH_ERROR: do_alert("Service search error",4000); break; case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS: do_alert("No records return",4000); break; case DiscoveryListener.SERVICE_SEARCH_TERMINATED: do_alert("Inquiry canceled",4000); break; } } public void servicesDiscovered(int i, ServiceRecord[] srs) { for(int x=0; x<srs.length;x++) services.addElement(srs[x]); try { btDevice.append(((RemoteDevice)devices.elementAt(currentDevice)).getFriendlyName(false),null); } catch (IOException ex) { System.out.println("service discover"+ex.getMessage()); } } public void do_alert(String msg, int time_out){ if(display.getCurrent() instanceof Alert){ ((Alert)display.getCurrent()).setString(msg); ((Alert)display.getCurrent()).setTimeout(time_out); }else{ Alert alert = new Alert("Bluetooth"); alert.setString(msg); alert.setTimeout(time_out); display.setCurrent(alert); } } private String getData(){ System.out.println("getData"); String cmd=""; try { ServiceRecord service = (ServiceRecord)services.elementAt(btDevice.getSelectedIndex()); String url = service.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false); conn = (StreamConnection)Connector.open(url); DataInputStream in = conn.openDataInputStream(); int i=0; timer.schedule(task, 15000); char c1; while(time){ //while(((c1 = in.readChar())>0) && (c1 != '\n')){ //while(((c1 = in.readChar())>0) ){ c1 = in.readChar(); cmd = cmd + c1; //System.out.println(c1); // } } System.out.print("cmd"+cmd); if(time == false){ in.close(); conn.close(); } } catch (IOException ex) { System.err.println("Cant read data"+ex); } return cmd; } //timer task fungsinya ketika telah mencapai waktu yg dijadwalkan putus koneksi private static class TestTimerTask extends TimerTask{ public TestTimerTask() { } public void run() { time = false; } } }

    Read the article

  • Trying to randomise a jQuery content slider

    - by alecrust
    Hi everyone, I'm using a very nice jQuery content slider called Easy Slider on my site that I downloaded from Css Globe. The script is excellent and does just what I want - except I can't make it randomise the list, it always scrolls from left to right or right to left! I'm far from good with JavaScript, so my attempts at solving this have been feeble. Although I'm sure it must be an easy fix! If anyone wouldn't mind taking a glance over the script to see if they can spot what I need to change to make it random it would be greatly appreciated! I've tried contacting the original plugin developer but have had no response yet. The comments on the Easy Slider page didn't bear much fruit either unfortunately. I've pasted the script I'm using on my site below: /* * Easy Slider 1.7 - jQuery plugin * written by Alen Grakalic * http://cssglobe.com/post/4004/easy-slider-15-the-easiest-jquery-plugin-for-sliding * * Copyright (c) 2009 Alen Grakalic (http://cssglobe.com) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * Built for jQuery library * http://jquery.com * */ (function($) { $.fn.easySlider = function(options){ // default configuration properties var defaults = { prevId: 'prevBtn', prevText: 'Previous', nextId: 'nextBtn', nextText: 'Next', controlsShow: true, controlsBefore: '', controlsAfter: '', controlsFade: true, firstId: 'firstBtn', firstText: 'First', firstShow: false, lastId: 'lastBtn', lastText: 'Last', lastShow: false, vertical: false, speed: 800, auto: false, pause: 7000, continuous: false, numeric: false, numericId: 'controls' }; var options = $.extend(defaults, options); this.each(function() { var obj = $(this); var s = $("li", obj).length; var w = $("li", obj).width(); var h = $("li", obj).height(); var clickable = true; obj.width(w); obj.height(h); obj.css("overflow","hidden"); var ts = s-1; var t = 0; $("ul", obj).css('width',s*w); if(options.continuous){ $("ul", obj).prepend($("ul li:last-child", obj).clone().css("margin-left","-"+ w +"px")); $("ul", obj).append($("ul li:nth-child(2)", obj).clone()); $("ul", obj).css('width',(s+1)*w); }; if(!options.vertical) $("li", obj).css('float','left'); if(options.controlsShow){ var html = options.controlsBefore; if(options.numeric){ html += '<ol id="'+ options.numericId +'"></ol>'; } else { if(options.firstShow) html += '<span id="'+ options.firstId +'"><a href=\"javascript:void(0);\">'+ options.firstText +'</a></span>'; html += ' <span id="'+ options.prevId +'"><a href=\"javascript:void(0);\">'+ options.prevText +'</a></span>'; html += ' <span id="'+ options.nextId +'"><a href=\"javascript:void(0);\">'+ options.nextText +'</a></span>'; if(options.lastShow) html += ' <span id="'+ options.lastId +'"><a href=\"javascript:void(0);\">'+ options.lastText +'</a></span>'; }; html += options.controlsAfter; $(obj).after(html); }; if(options.numeric){ for(var i=0;i<s;i++){ $(document.createElement("li")) .attr('id',options.numericId + (i+1)) .html('<a rel='+ i +' href=\"javascript:void(0);\">'+ (i+1) +'</a>') .appendTo($("#"+ options.numericId)) .click(function(){ animate($("a",$(this)).attr('rel'),true); }); }; } else { $("a","#"+options.nextId).click(function(){ animate("next",true); }); $("a","#"+options.prevId).click(function(){ animate("prev",true); }); $("a","#"+options.firstId).click(function(){ animate("first",true); }); $("a","#"+options.lastId).click(function(){ animate("last",true); }); }; function setCurrent(i){ i = parseInt(i)+1; $("li", "#" + options.numericId).removeClass("current"); $("li#" + options.numericId + i).addClass("current"); }; function adjust(){ if(t>ts) t=0; if(t<0) t=ts; if(!options.vertical) { $("ul",obj).css("margin-left",(t*w*-1)); } else { $("ul",obj).css("margin-left",(t*h*-1)); } clickable = true; if(options.numeric) setCurrent(t); }; function animate(dir,clicked){ if (clickable){ clickable = false; var ot = t; switch(dir){ case "next": t = (ot>=ts) ? (options.continuous ? t+1 : ts) : t+1; break; case "prev": t = (t<=0) ? (options.continuous ? t-1 : 0) : t-1; break; case "first": t = 0; break; case "last": t = ts; break; default: t = dir; break; }; var diff = Math.abs(ot-t); var speed = diff*options.speed; if(!options.vertical) { p = (t*w*-1); $("ul",obj).animate( { marginLeft: p }, { queue:false, duration:speed, complete:adjust } ); } else { p = (t*h*-1); $("ul",obj).animate( { marginTop: p }, { queue:false, duration:speed, complete:adjust } ); }; if(!options.continuous && options.controlsFade){ if(t==ts){ $("a","#"+options.nextId).hide(); $("a","#"+options.lastId).hide(); } else { $("a","#"+options.nextId).show(); $("a","#"+options.lastId).show(); }; if(t==0){ $("a","#"+options.prevId).hide(); $("a","#"+options.firstId).hide(); } else { $("a","#"+options.prevId).show(); $("a","#"+options.firstId).show(); }; }; if(clicked) clearTimeout(timeout); if(options.auto && dir=="next" && !clicked){; timeout = setTimeout(function(){ animate("next",false); },diff*options.speed+options.pause); }; }; }; // init var timeout; if(options.auto){; timeout = setTimeout(function(){ animate("next",false); },options.pause); }; if(options.numeric) setCurrent(0); if(!options.continuous && options.controlsFade){ $("a","#"+options.prevId).hide(); $("a","#"+options.firstId).hide(); }; }); }; })(jQuery); Many thanks again! Alec

    Read the article

  • questions regarding the use of A* with the 15-square puzzle

    - by Cheeso
    I'm trying to build an A* solver for a 15-square puzzle. The goal is to re-arrange the tiles so that they appear in their natural positions. You can only slide one tile at a time. Each possible state of the puzzle is a node in the search graph. For the h(x) function, I am using an aggregate sum, across all tiles, of the tile's dislocation from the goal state. In the above image, the 5 is at location 0,0, and it belongs at location 1,0, therefore it contributes 1 to the h(x) function. The next tile is the 11, located at 0,1, and belongs at 2,2, therefore it contributes 3 to h(x). And so on. EDIT: I now understand this is what they call "Manhattan distance", or "taxicab distance". I have been using a step count for g(x). In my implementation, for any node in the state graph, g is just +1 from the prior node's g. To find successive nodes, I just examine where I can possibly move the "hole" in the puzzle. There are 3 neighbors for the puzzle state (aka node) that is displayed: the hole can move north, west, or east. My A* search sometimes converges to a solution in 20s, sometimes 180s, and sometimes doesn't converge at all (waited 10 mins or more). I think h is reasonable. I'm wondering if I've modeled g properly. In other words, is it possible that my A* function is reaching a node in the graph via a path that is not the shortest path? Maybe have I not waited long enough? Maybe 10 minutes is not long enough? For a fully random arrangement, (assuming no parity problems), What is the average number of permutations an A* solution will examine? (please show the math) I'm going to look for logic errors in my code, but in the meantime, Any tips? (ps: it's done in Javascript). Also, no, this isn't CompSci homework. It's just a personal exploration thing. I'm just trying to learn Javascript. EDIT: I've found that the run-time is highly depend upon the heuristic. I saw the 10x factor applied to the heuristic from the article someone mentioned, and it made me wonder - why 10x? Why linear? Because this is done in javascript, I could modify the code to dynamically update an html table with the node currently being considered. This allowd me to peek at the algorithm as it was progressing. With a regular taxicab distance heuristic, I watched as it failed to converge. There were 5's and 12's in the top row, and they kept hanging around. I'd see 1,2,3,4 creep into the top row, but then they'd drop out, and other numbers would move up there. What I was hoping to see was 1,2,3,4 sort of creeping up to the top, and then staying there. I thought to myself - this is not the way I solve this personally. Doing this manually, I solve the top row, then the 2ne row, then the 3rd and 4th rows sort of concurrently. So I tweaked the h(x) function to more heavily weight the higher rows and the "lefter" columns. The result was that the A* converged much more quickly. It now runs in 3 minutes instead of "indefinitely". With the "peek" I talked about, I can see the smaller numbers creep up to the higher rows and stay there. Not only does this seem like the right thing, it runs much faster. I'm in the process of trying a bunch of variations. It seems pretty clear that A* runtime is very sensitive to the heuristic. Currently the best heuristic I've found uses the summation of dislocation * ((4-i) + (4-j)) where i and j are the row and column, and dislocation is the taxicab distance. One interesting part of the result I got: with a particular heuristic I find a path very quickly, but it is obviously not the shortest path. I think this is because I am weighting the heuristic. In one case I got a path of 178 steps in 10s. My own manual effort produce a solution in 87 moves. (much more than 10s). More investigation warranted. So the result is I am seeing it converge must faster, and the path is definitely not the shortest. I have to think about this more. Code: var stop = false; function Astar(start, goal, callback) { // start and goal are nodes in the graph, represented by // an array of 16 ints. The goal is: [1,2,3,...14,15,0] // Zero represents the hole. // callback is a method to call when finished. This runs a long time, // therefore we need to use setTimeout() to break it up, to avoid // the browser warning like "Stop running this script?" // g is the actual distance traveled from initial node to current node. // h is the heuristic estimate of distance from current to goal. stop = false; start.g = start.dontgo = 0; // calcHeuristic inserts an .h member into the array calcHeuristicDistance(start); // start the stack with one element var closed = []; // set of nodes already evaluated. var open = [ start ]; // set of nodes to evaluate (start with initial node) var iteration = function() { if (open.length==0) { // no more nodes. Fail. callback(null); return; } var current = open.shift(); // get highest priority node // update the browser with a table representation of the // node being evaluated $("#solution").html(stateToString(current)); // check solution returns true if current == goal if (checkSolution(current,goal)) { // reconstructPath just records the position of the hole // through each node var path= reconstructPath(start,current); callback(path); return; } closed.push(current); // get the set of neighbors. This is 3 or fewer nodes. // (nextStates is optimized to NOT turn directly back on itself) var neighbors = nextStates(current, goal); for (var i=0; i<neighbors.length; i++) { var n = neighbors[i]; // skip this one if we've already visited it if (closed.containsNode(n)) continue; // .g, .h, and .previous get assigned implicitly when // calculating neighbors. n.g is nothing more than // current.g+1 ; // add to the open list if (!open.containsNode(n)) { // slot into the list, in priority order (minimum f first) open.priorityPush(n); n.previous = current; } } if (stop) { callback(null); return; } setTimeout(iteration, 1); }; // kick off the first iteration iteration(); return null; }

    Read the article

  • Javascript or CSS hover not working in Safari and Chrome

    - by PAZtech
    I have a problem with a script for a image gallery. The problem seems to only occur on Safari and Chrome, but if I refresh the page I get it to work correctly - weird! Correct function: The gallery has a top bar, which if you hover over it, it will display a caption. Below sits the main image. At the bottom there is another bar that is a reversal of the top bar. When you hover over it, it will display thumbnails of the gallery. The problem: In Safari and Chrome, the thumbnail holder will not display. In fact, it doesn't even show it as an active item (or a rollover). But oddly enough, if you manually refresh the page it begins to work correctly for the rest of the time you view the page. Once you have left the page and return the same error occurs again and you have to go through the same process. Here's one of the pages to look at: link text Here's the CSS: #ThumbsGutter { background: url(../Images/1x1.gif); background: url(/Images/1x1.gif); height: 105px; left: 0px; position: absolute; top: 0px; width: 754px; z-index: 2; } #ThumbsHolder { display: none; } #ThumbsTable { left: 1px; } #Thumbs { background-color: #000; width: 703px; } #Thumbs ul { list-style: none; margin: 0; padding: 0; } #Thumbs ul li { display: inline; } .Thumbs ul li a { border-right: 1px solid #fff; border-top: 1px solid #fff; float: left; left: 1px; } .Thumbs ul li a img { filter: alpha(opacity=50); height: 104px; opacity: .5; width: 140px; } .Thumbs ul li a img.Hot { filter: alpha(opacity=100); opacity: 1; } Here is the javascript: //Variables var globalPath = ""; var imgMain; var gutter; var holder; var thumbs; var loadingImage; var holderState; var imgCount; var imgLoaded; var captionHolder; var captionState = 0; var captionHideTimer; var captionHideTime = 500; var thumbsHideTimer; var thumbsHideTime = 500; $(document).ready(function() { //Load Variables imgMain = $("#MainImage"); captionHolder = $("#CaptionHolder"); gutter = $("#ThumbsGutter"); holder = $("#ThumbsHolder"); thumbs = $("#Thumbs"); loadingImage = $("#LoadingImageHolder"); //Position Loading Image loadingImage.centerOnObject(imgMain); //Caption Tab Event Handlers $("#CaptionTab").mouseover(function() { clearCaptionHideTimer(); showCaption(); }).mouseout(function() { setCaptionHideTimer(); }); //Caption Holder Event Handlers captionHolder.mouseenter(function() { clearCaptionHideTimer(); }).mouseleave(function() { setCaptionHideTimer(); }); //Position Gutter if (jQuery.browser.safari) { gutter.css("left", imgMain.position().left + "px").css("top", ((imgMain.offset().top + imgMain.height()) - 89) + "px"); } else { gutter.css("left", imgMain.position().left + "px").css("top", ((imgMain.offset().top + imgMain.height()) - 105) + "px"); } //gutter.css("left", imgMain.position().left + "px").css("top", ((imgMain.offset().top + imgMain.height()) - 105) + "px"); //gutter.css("left", imgMain.offset().left + "px").css("top", ((imgMain.offset().top + imgMain.height()) - gutter.height()) + "px"); //Thumb Tab Event Handlers $("#ThumbTab").mouseover(function() { clearThumbsHideTimer(); showThumbs(); }).mouseout(function() { setThumbsHideTimer(); }); //Gutter Event Handlers gutter.mouseenter(function() { //showThumbs(); clearThumbsHideTimer(); }).mouseleave(function() { //hideThumbs(); setThumbsHideTimer(); }); //Next/Prev Button Event Handlers $("#btnPrev").mouseover(function() { $(this).attr("src", globalPath + "/Images/GalleryLeftButtonHot.jpg"); }).mouseout(function() { $(this).attr("src", globalPath + "/Images/GalleryLeftButton.jpg"); }); $("#btnNext").mouseover(function() { $(this).attr("src", globalPath + "/Images/GalleryRightButtonHot.jpg"); }).mouseout(function() { $(this).attr("src", globalPath + "/Images/GalleryRightButton.jpg"); }); //Load Gallery //loadGallery(1); }); function loadGallery(galleryID) { //Hide Holder holderState = 0; holder.css("display", "none"); //Hide Empty Gallery Text $("#EmptyGalleryText").css("display", "none"); //Show Loading Message $("#LoadingGalleryOverlay").css("display", "inline").centerOnObject(imgMain); $("#LoadingGalleryText").css("display", "inline").centerOnObject(imgMain); //Load Thumbs thumbs.load(globalPath + "/GetGallery.aspx", { GID: galleryID }, function() { $("#TitleHolder").html($("#TitleContainer").html()); $("#DescriptionHolder").html($("#DescriptionContainer").html()); imgCount = $("#Thumbs img").length; imgLoaded = 0; if (imgCount == 0) { $("#LoadingGalleryText").css("display", "none"); $("#EmptyGalleryText").css("display", "inline").centerOnObject(imgMain); } else { $("#Thumbs img").load(function() { imgLoaded++; if (imgLoaded == imgCount) { holder.css("display", "inline"); //Carousel Thumbs thumbs.jCarouselLite({ btnNext: "#btnNext", btnPrev: "#btnPrev", mouseWheel: true, scroll: 1, visible: 5 }); //Small Image Event Handlers $("#Thumbs img").each(function(i) { $(this).mouseover(function() { $(this).addClass("Hot"); }).mouseout(function() { $(this).removeClass("Hot"); }).click(function() { //Load Big Image setImage($(this)); }); }); holder.css("display", "none"); //Load First Image var img = new Image(); img.onload = function() { imgMain.attr("src", img.src); setCaption($("#Image1").attr("alt")); //Hide Loading Message $("#LoadingGalleryText").css("display", "none"); $("#LoadingGalleryOverlay").css("display", "none"); } img.src = $("#Image1").attr("bigimg"); } }); } }); } function showCaption() { if (captionState == 0) { $("#CaptionTab").attr("src", globalPath + "/Images/CaptionTabHot.jpg"); captionHolder.css("display", "inline").css("left", imgMain.position().left + "px").css("top", imgMain.position().top + "px").css("width", imgMain.width() + "px").effect("slide", { "direction": "up" }, 500, function() { captionState = 1; }); } } function hideCaption() { if (captionState == 1) { captionHolder.toggle("slide", { "direction": "up" }, 500, function() { $("#CaptionTab").attr("src", globalPath + "/Images/CaptionTab.jpg"); captionState = 0; }); } } function setCaptionHideTimer() { captionHideTimer = window.setTimeout(hideCaption,captionHideTime); } function clearCaptionHideTimer() { if(captionHideTimer) { window.clearTimeout(captionHideTimer); captionHideTimer = null; } } function showThumbs() { if (holderState == 0) { $("#ThumbTab").attr("src", globalPath + "/Images/ThumbTabHot.jpg"); holder.effect("slide", { "direction": "down" }, 500, function() { holderState = 1; }); } } function hideThumbs() { if (holderState == 1) { if (jQuery.browser.safari) { holder.css("display", "none"); $("#ThumbTab").attr("src", globalPath + "/Images/ThumbTab.jpg"); holderState = 0; } else { holder.toggle("slide", { "direction": "down" }, 500, function() { $("#ThumbTab").attr("src", globalPath + "/Images/ThumbTab.jpg"); holderState = 0; }); } } } function setThumbsHideTimer() { thumbsHideTimer = window.setTimeout(hideThumbs,thumbsHideTime); } function clearThumbsHideTimer() { if(thumbsHideTimer) { window.clearTimeout(thumbsHideTimer); thumbsHideTimer = null; } } function setImage(image) { //Show Loading Image loadingImage.css("display", "inline"); var img = new Image(); img.onload = function() { //imgMain.css("background","url(" + img.src + ")").css("display","none").fadeIn(250); imgMain.attr("src", img.src).css("display", "none").fadeIn(250); setCaption(image.attr("alt")); //Hide Loading Image loadingImage.css("display", "none"); }; img.src = image.attr("bigimg"); } function setCaption(caption) { $("#CaptionText").html(caption); //alert($("#CaptionText").html()); /* if (caption.length 0) { $("#CaptionText") .css("display", "inline") .css("left", imgMain.position().left + "px") .css("top", imgMain.position().top + "px") .css("width", imgMain.width() + "px") .html(caption); $("#CaptionOverlay").css("display", "inline") .css("height", $("#CaptionText").height() + 36 + "px") .css("left", imgMain.position().left + "px") .css("top", imgMain.position().top + "px") .css("width", imgMain.width() + "px"); } else { $("#CaptionText").css("display", "none"); $("#CaptionOverlay").css("display", "none"); } */ } Please if anyone could help, it would be greatly appreciated! Thanks in advance. Justin

    Read the article

  • jQuery "Microsoft JScript runtime error: Object expected"

    - by Oskar Kjellin
    I have the below code that does not seem to work at all :( I keep getting: Microsoft JScript runtime error: Object expected The error seems to occur when the timeout is done. So if I raise the timeout with 10 seconds the error holds for another 10 seconds. I want to be able to update the number of friends online async. The number is shown with the following html: <a href="" id="showChat" >Friends online <strong id="friendsOnline">(?)</strong></a> The friends part is set at the first run, but when the timeout calls back it does not fire again. Also, I cannot see on which line the error occurs because if I want to break on the error it just shows "no source code" etc. The code below is the code I'm using. Thanks! <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.js" type="text/javascript"></script> <script src='/Scripts/MicrosoftAjax.js' type="text/javascript"></script> <script src='/Scripts/MicrosoftMvcAjax.js' type="text/javascript"></script> <script src='/Scripts/jquery.autocomplete.js' type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { UpdateFriendsOnline(); function UpdateFriendsOnline() { window.setTimeout("UpdateFriendsOnline()", 1000); $.get("/Account/GetFriendsOnline", function(data) { $("#friendsOnline").html("(" + data + ")"); }); } }); </script>

    Read the article

  • Scrollbar problem with jquery ui dialog in Chrome and Safari

    - by alexis.kennedy
    I'm using the jquery ui dialog with modal=true. In Chrome and Safari, this disables scrolling via the scroll bar and cursor keys (scrolling with the mouse wheel and page up/down still works). This is a problem if the dialog is too tall to fit on one page - users on a laptop get frustrated. Someone raised this three months ago on the jquery bug tracker - http://dev.jqueryui.com/ticket/4671 - it doesn't look like fixing it is a priority. :) So does anyone (i) have a fix for this? (ii) have a suggested workaround that would give a decent usability experience? I'm experimenting with mouseover / scrollto on bits of the form, but it's not a great solution :( EDIT: props to Rowan Beentje (who's not on SO afaict) for finding a solution to this. jQueryUI prevents scrolling by capturing the mouseup / mousedown events. So this: $("dialogId").dialog({ open: function(event, ui) { window.setTimeout(function() { jQuery(document) .unbind('mousedown.dialog-overlay') .unbind('mouseup.dialog-overlay') ; }, 100); }, modal: true}); seems to fix it. Use at own risk, I don't know what other unmodal behaviour unbinding this stuff might allow.

    Read the article

  • Force Postback from code behind? Or reload JavaScript from an Asynchronous Postback?

    - by sah302
    Hi all, I've got a Jquery UI dialog that pops up to confirm the creation of an item after filling out a form. I have the form in an update panel due to various needs of the form, and especially because I want validation being done on the form without reloading the page. JavaScript appears to not reload on an asynchronoous postback. This means when the form is a success and I change the variable 'formSubmitPass' to true, it does not get passed to the Javascript via <%= formSubmitPass %. If I add a trigger to the submit button to do a full postback, it works. However I don't want the submit button to do a full postback as I said so I can validate the form within the update panel. How can I have this so my form validates asynchronously, but my javaScript will properly reload when the form is completed successfully and the item is saved to the database? Javascript: var formSubmitPass = '<%= formSubmitPass %>'; var redirectUrl = '<%= redirectUrl %>'; function pageLoad() { $('#formPassBox').dialog({ autoOpen: false, width: 400, resizable: false, modal: true, draggable: false, buttons: { "Ok": function() { window.location.href = redirectUrl; } }, open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); var t = window.setTimeout("goToUrl()", 5000); } }); if(formSubmitPass == 'True') { $('#formPassBox').dialog({ autoOpen: true }); } So how can I force a postback from the code behind, or reload the JavaScript on an Asynchronous Postback, or do this in a way that will work such that I can continue to do Async form validation? Edit: I change formSubmitPass at the very end of the code behind: If errorCount = 0 Then formSubmitPass = True upForm.Update() Else formSubmitPass = False End If So on a full postback, the value does change.

    Read the article

  • Selenium error on Win7

    - by hawkeye
    I'm starting Selenium server with the following on a command line: java -jar selenium-server.jar Here is the code: import com.thoughtworks.selenium.*; import java.util.regex.Pattern; import org.openqa.selenium.server.SeleniumServer; import junit.framework.*; public class orkut extends SeleneseTestCase { public void setUp() throws Exception { //SeleniumServer server = new SeleniumServer(); //server.start(); setUp("https://www.google.com/", "*firefox C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"); } public void testOrkut() throws Exception { selenium.setTimeout("10000"); selenium.open("/accounts/ServiceLogin?service=orkut&hl=en-US&rm=false&continue=http%3A%2F%2Fwww.orkut.com%2FRedirLogin%3Fmsg%3D0&cd=IN&skipvpage=true&sendvemail=false"); selenium.type("Email", "username"); selenium.type("Passwd", "password"); selenium.click("signIn"); selenium.selectFrame("orkutFrame"); selenium.click("link=Communities"); selenium.waitForPageToLoad("10000"); } public static Test suite() { return new TestSuite(orkut.class); } public void tearDown(){ selenium.stop(); } public static void main(String args[]) { junit.textui.TestRunner.run(suite()); } } Here is the error: .E Time: 33.386 There was 1 error: 1) testOrkut(orkut)java.lang.RuntimeException: Could not start Selenium session: Failed to start new browser session: Unable to delete file C:\Users\user\AppData\Local\Temp\customProfileDir78cf02e3efca4772a71525c4a7523cac\parent.lock at com.thoughtworks.selenium.DefaultSelenium.start(DefaultSelenium.java:89) at com.thoughtworks.selenium.SeleneseTestBase.setUp(SeleneseTestBase.java:123) at com.thoughtworks.selenium.SeleneseTestBase.setUp(SeleneseTestBase.java:104) at com.thoughtworks.selenium.SeleneseTestCase.setUp(SeleneseTestCase.java:78) at orkut.setUp(orkut.java:14) at com.thoughtworks.selenium.SeleneseTestCase.runBare(SeleneseTestCase.java:212) at orkut.main(orkut.java:37) Caused by: com.thoughtworks.selenium.SeleniumException: Failed to start new browser session: Unable to delete file C:\Users\M022534\AppData\Local\Temp\customProfileDir78cf02e3efca4772a71525c4a7523cac\parent.lock at com.thoughtworks.selenium.HttpCommandProcessor.throwAssertionFailureExceptionOrError(HttpCommandProcessor.java:97) at com.thoughtworks.selenium.HttpCommandProcessor.doCommand(HttpCommandProcessor.java:91) at com.thoughtworks.selenium.HttpCommandProcessor.getString(HttpCommandProcessor.java:262) at com.thoughtworks.selenium.HttpCommandProcessor.start(HttpCommandProcessor.java:223) at com.thoughtworks.selenium.DefaultSelenium.start(DefaultSelenium.java:81) ... 16 more FAILURES!!! Tests run: 1, Failures: 0, Errors: 1

    Read the article

  • jQuery modal Dialog over iFrame

    - by Ram
    I am using jQuery UI dialog for modal popups. I have some iframes in my page as well. The iFrame (z-Index = 1500) sits on top of the parent page (z-index =1000). I open the modal dialog from the parent page. I am trying to set the z-index using $('modal').dialog('option','zIndex',3000); but this is not working. I also tried stack:true (to stack it on top), and .dialog( 'moveToTop' ) as well, but they don't seem to work. Here is the code: Parent page: using style sheet : from "css/ui-darkness/jquery-ui-1.7.2.custom.css" using scripts: jquery-1.3.2.min.js && jquery-ui-1.7.2.custom.min.js <script type="text/javascript" language="javascript"> function TestModal() { var modal = "<div id='modal'>Hello popup world</div>"; $(modal).dialog({ modal: true, title: 'Modal Popup', zIndex: 12000, // settin it here works, but I want to set it at runtime instead of setting it at design time close: function() { setTimeout(TestModal, 5000); $(this).remove(); } }); $('modal').dialog('option', 'zIndex', 11000); // these dont work $('modal').dialog('moveToTop'); // these dont work $('modal').dialog('option', 'stack', true); // these dont work } /** Run with defaults **/ $(document).ready(function() { TestModal(); }); </script> <div> Hello World <br /> </div> <iframe src="blocker.htm" width="100%" height="100%" frameborder="0" scrolling="no" name="myInlineFrame" style="z-index:10000;background-color:Gray;position:absolute;top:0px;left:0px" ALLOWTRANSPARENCY="false"> </iframe> iframe : blocker.htm .wrap{width:100%;height:100%} I am an iframe and I am evil

    Read the article

< Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >