Search Results

Search found 37529 results on 1502 pages for 'charateristic function'.

Page 5/1502 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Redefining PHP function?

    - by Michael
    If I have a function: function this($a){ return $a; } If I wanted to redefine the function, would it be as simple as rewriting it? function this($a, $b){ //New this function return $a * $b; }

    Read the article

  • Javascript AJAX function returns undefined instead of true / false

    - by Josh K
    I have a function that issues an AJAX call (via jQuery). In the complete section I have a function that says: complete: function(XMLHttpRequest, textStatus) { if(textStatus == "success") { return(true); } else { return(false); } } However, if I call this like so: if(callajax()) { // Do something } else { // Something else } The first is never called. If I put an alert(textStatus) in the complete function I get true, but not before that function returns undefined.

    Read the article

  • Inverted function keys (F1-F12) on HP Pavilion dv4t

    - by The Electric Muffin
    (I know there have already been a lot of questions about this, but none of them mentioned the dv4t specifically.) I'm thinking about getting an HP Pavilion dv4t-4200 or -5100, but something that's really irritating me is that by default the function keys (F1-F12) are "inverted"—without holding the Fn key, the function keys do things like change the brightness, change or mute the volume, and switch to an external display. Only if you hold Fn will they actually produce F1, F2, etc. This is not how keyboards are supposed to work. Is there any way to disable this "feature" that has been verified to work on the HP Pavilion dv4t-4200 or HP Pavilion dv4t-5100? I don't want to buy this computer unless this is possible.

    Read the article

  • How to change a function/formula in a whole column where I also have empty cells

    - by Zvi
    I have a column with a formula/function that has other cells as parameters. However in the column, every few rows I have a subtotal and blanks, for readability. Now I decided to change the formula/function but I can not do copy+paste on the whole column because of the subtotals/blank cells, and I can not do change+replace because there are parameters in the functions that uses other cells and thus it is different in each cell in the column. For example, if the formula is =if(A5>24,1,"") and I want to change it to =AA_userfn(A5,B5) Any idea how to change it easily? currently I copy+paste few rows at a time, but that is tedious. Maybe a Sub that will go all over the column (the column number as an input parameter) and looks for =if(, and then replaces it with =aa_userfn(Ax, By) where Ax and By are calculated based on the position of the cell currently changed in reference to the previous values in that cell. Any ideas will be welcomed

    Read the article

  • Special function keys are mixed up on my Macbook Pro

    - by seanieb
    I recently sent my Macbook Pro (late 2008 model) to get a replaced logic board and top cover. When I got it back the Special function keys are mixed up. F3 - mutes sound - it should do expose f4 - decreases volume - it should show the dashboard f5 - increases volume ....etc, ... F11 - expose - it should decrease volume f12 - dashboard - it should increase volume I have checked and made sure that System PreferencesKeyboard"use all F keys as standard function keys" is not selected. And that no accessibility options are switched on either. How do I fix this? or should I bring it back to the repair shop? Thanks

    Read the article

  • How to make this jquery function reusable?

    - by Pandiya Chendur
    Hai this is my jquery function, function getRecordspage(curPage, pagSize) { $.ajax({ type: "POST", url: "Default.aspx/GetRecords", data: "{'currentPage':" + curPage + ",'pagesize':" + pagSize + "}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(jsonObj) { var strarr = jsonObj.d.split('##'); var jsob = jQuery.parseJSON(strarr[0]); $.each(jsob.Table, function(i, employee) { $('<div class="resultsdiv"><br /><span class="resultName">' + employee.Emp_Name + '</span><span class="resultfields" style="padding-left:100px;">Category&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.Desig_Name + '</span><br /><br /><span id="SalaryBasis" class="resultfields">Salary Basis&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.SalaryBasis + '</span><span class="resultfields" style="padding-left:25px;">Salary&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.FixedSalary + '</span><span style="font-size:110%;font-weight:bolder;padding-left:25px;">Address&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.Address + '</span></div>').appendTo('#ResultsDiv'); }); $(".resultsdiv:even").addClass("resultseven"); $(".resultsdiv").hover(function() { $(this).addClass("resultshover"); }, function() { $(this).removeClass("resultshover"); }); } }); } In my page i have this jquery script, $("#lnkbtn0").click(function() { getRecordspage(1, 5) }); And my page has <a ID="lnkbtn0" class="page-numbers">1</a> <a ID="lnkbtn1" class="page-numbers">2</a> <a ID="lnkbtn2" class="page-numbers">3</a> <a ID="lnkbtn3" class="page-numbers">4</a> How to make other link buttons to call this function with diff curPage parameter...

    Read the article

  • Codeigniter: Library function--I'm stuck

    - by Kevin Brown
    I have a library function that sets up my forms, and submits data. They're long, and they work, so I'll spare you reading my code. :) I simply need a way for my functions to determine how to handle the data. Until now, the function did one thing: Submit a report for the current user. NOW, the client has requested that an administrator also be able to complete a form--this means that the form would be filled out, and it would CREATE a user at the same time, whereas the current function EDITS and is accessed by an EXISTING user. Do I need a separate function to do essentially the same thing? How do I make one function perform two tasks? One to update a user, and if there is no user, create one. Current controller: function survey() { $id = $this->session->userdata('id'); $data['member'] = $this->home_model->getUser($id); //Convert the db Object to a row array $data['manager'] = $data['member']->row(); $manager_id = $data['manager']->manager_id; $data['manager'] = $this->home_model->getUser($manager_id); $data['manager'] = $data['manager']->row(); $data['header'] = "Home"; $this->survey_form_processing->survey_form($this->_container,$data, $method); } Current Library: function survey_form($container) { //Lots of validation stuff $this->CI->validation->set_rules($rules); if ( $this->CI->validation->run() === FALSE ) { // Output any errors $this->CI->validation->output_errors(); } else { // Submit form $this->_submit(); } $this->CI->load->view($container,$data); The submit function is huge too. Basically says, "Update table with data where user_id=current user" I hope this wasn't too confusing. I'll create two functions if need be, but I'd like to keep redundancy down! }

    Read the article

  • SQL SERVER – Detecting Leap Year in T-SQL using SQL Server 2012 – IIF, EOMONTH and CONCAT Function

    - by pinaldave
    Note: Tomorrow is February 29th. This blog post is dedicated to coming tomorrow – a special day :) Subu: “How can I find leap year in using SQL Server 2012?“ Pinal: “Are you asking me how to year 2012 is leap year using T-SQL – search online and you will find many example of the same.” Subu: “No. I am asking – How can I find leap year in using SQL Server 2012?“ Pinal: “Oh so you are asking – How can I find leap year in using SQL Server 2012?“ Subu: “Yeah - How can I find leap year in using SQL Server 2012?“ Pinal: “Let me do that for you – How can you find leap year in using SQL Server 2012?“ Indeed a fun conversation. Honestly, only reason I pasted our conversation here is – it was fun. What he was asking is that how to do it using new functions introduced in SQL Server 2012. Here is the article I have written which introduces all the new functions in SQL Server 2012 Summary of All the Analytic Functions – MSDN and SQLAuthority and 14 New Functions – A Quick Guide. There are many functions written to figure out to figure out if any year is Leap Year or not. The same I have written using T-SQL function over here. CREATE FUNCTION dbo.IsLeapYear (@year INT) RETURNS INT AS BEGIN RETURN(IIF(DATEPART(dd,(EOMONTH(CONCAT(@year,'0201')))) = 29,1,0)) END GO What I really like is that I was able to use three newly introduced function in SQL Server 2012 in above script. You can read more about them here. IIF, EOMONTH and CONCAT. You can validate above query by running following script. SELECT dbo.IsLeapYear('2011') 'IsLeapYear'; SELECT dbo.IsLeapYear('2012') 'IsLeapYear'; GO You will get result 1 if the year is leap year and 0 if year is not leap year. Reference: Pinal Dave (http://blog.sqlauthority.com) Filed under: PostADay, SQL, SQL Authority, SQL DateTime, SQL Function, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology

    Read the article

  • Problem inserting parameters into a function

    - by SoLoGHoST
    Ok, I am trying to place parameters into a function that is called like so: $parameters['function']($parameters['params']); Here is the function and the parameters that I need to be placed into this: $parameters['function'] = 'test_error'; $parameters['params'] = array(0 => $txt['sometext'], 1 => 'critical', 2 => true); The test_error function takes 3 parameters: The error to output The type of error noted within a string value ('general', 'critical', etc. etc.). Whether it should be echoed or not. Here is the output I get: Here is a test error.ArraycriticalArray1 I know this function works perfect, but it only gives me the 1st parameter returned from it. What am I doing wrong here with the $parameters['params']??

    Read the article

  • Jquery Live Function

    - by marharépa
    Hi! I want to make this script to work as LIVE() function. Please help me! $(".img img").each(function() { $(this).cjObjectScaler({ destElem: $(this).parent(), method: "fit" }); }); the cjObjectScaler script (called in the html header) is this: (thanks for Doug Jones) (function ($) { jQuery.fn.imagesLoaded = function (callback) { var elems = this.filter('img'), len = elems.length; elems.bind('load', function () { if (--len <= 0) { callback.call(elems, this); } }).each(function () { // cached images don't fire load sometimes, so we reset src. if (this.complete || this.complete === undefined) { var src = this.src; // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f this.src = '#'; this.src = src; } }); }; })(jQuery); /* CJ Object Scaler */ (function ($) { jQuery.fn.cjObjectScaler = function (options) { /* user variables (settings) ***************************************/ var settings = { // must be a jQuery object method: "fill", // the parent object to scale our object into destElem: null, // fit|fill fade: 0 // if positive value, do hide/fadeIn }; /* system variables ***************************************/ var sys = { // function parameters version: '2.1.1', elem: null }; /* scale the image ***************************************/ function scaleObj(obj) { // declare some local variables var destW = jQuery(settings.destElem).width(), destH = jQuery(settings.destElem).height(), ratioX, ratioY, scale, newWidth, newHeight, borderW = parseInt(jQuery(obj).css("borderLeftWidth"), 10) + parseInt(jQuery(obj).css("borderRightWidth"), 10), borderH = parseInt(jQuery(obj).css("borderTopWidth"), 10) + parseInt(jQuery(obj).css("borderBottomWidth"), 10), objW = jQuery(obj).width(), objH = jQuery(obj).height(); // check for valid border values. IE takes in account border size when calculating width/height so just set to 0 borderW = isNaN(borderW) ? 0 : borderW; borderH = isNaN(borderH) ? 0 : borderH; // calculate scale ratios ratioX = destW / jQuery(obj).width(); ratioY = destH / jQuery(obj).height(); // Determine which algorithm to use if (!jQuery(obj).hasClass("cf_image_scaler_fill") && (jQuery(obj).hasClass("cf_image_scaler_fit") || settings.method === "fit")) { scale = ratioX < ratioY ? ratioX : ratioY; } else if (!jQuery(obj).hasClass("cf_image_scaler_fit") && (jQuery(obj).hasClass("cf_image_scaler_fill") || settings.method === "fill")) { scale = ratioX < ratioY ? ratioX : ratioY; } // calculate our new image dimensions newWidth = parseInt(jQuery(obj).width() * scale, 10) - borderW; newHeight = parseInt(jQuery(obj).height() * scale, 10) - borderH; // Set new dimensions & offset jQuery(obj).css({ "width": newWidth + "px", "height": newHeight + "px"//, // "position": "absolute", // "top": (parseInt((destH - newHeight) / 2, 10) - parseInt(borderH / 2, 10)) + "px", // "left": (parseInt((destW - newWidth) / 2, 10) - parseInt(borderW / 2, 10)) + "px" }).attr({ "width": newWidth, "height": newHeight }); // do our fancy fade in, if user supplied a fade amount if (settings.fade > 0) { jQuery(obj).fadeIn(settings.fade); } } /* set up any user passed variables ***************************************/ if (options) { jQuery.extend(settings, options); } /* main ***************************************/ return this.each(function () { sys.elem = this; // if they don't provide a destObject, use parent if (settings.destElem === null) { settings.destElem = jQuery(sys.elem).parent(); } // need to make sure the user set the parent's position. Things go bonker's if not set. // valid values: absolute|relative|fixed if (jQuery(settings.destElem).css("position") === "static") { jQuery(settings.destElem).css({ "position": "relative" }); } // if our object to scale is an image, we need to make sure it's loaded before we continue. if (typeof sys.elem === "object" && typeof settings.destElem === "object" && typeof settings.method === "string") { // if the user supplied a fade amount, hide our image if (settings.fade > 0) { jQuery(sys.elem).hide(); } if (sys.elem.nodeName === "IMG") { // to fix the weird width/height caching issue we set the image dimensions to be auto; jQuery(sys.elem).width("auto"); jQuery(sys.elem).height("auto"); // wait until the image is loaded before scaling jQuery(sys.elem).imagesLoaded(function () { scaleObj(this); }); } else { scaleObj(jQuery(sys.elem)); } } else { console.debug("CJ Object Scaler could not initialize."); return; } }); }; })(jQuery);

    Read the article

  • not returning anything from postgresql function?

    - by netllama
    Is it possible for a PostgreSQL plpgsql function to not return anything? I've created a function, and I don't need it to return anything at all, as it performs a complex SQL query, and inserts the results of that query into another table (SELECT INTO ....). Thus, I have no need or interest in having the function return any output or value. Unfortunately, when I try to omit the RETURN clause of the function declaration, I can't create the function. Is it possible for a PostgreSQL plpgsql function to not return anything?

    Read the article

  • VB .NET Shared Function if called multiple times simultaneously

    - by Mehdi Anis
    Consider I have a shared function:- Public Shared Function CalculateAreaFromRadius(ByVal radius As Double) As Double ' square the radius... Dim radiusSquared As Double radiusSquared = radius * radius ' multiply it by pi... Dim result As Double result = radiusSquared * Math.PI 'Wait a bit, for the sake of testing and 'simulate another call will be made b4 earlier one ended or such for i as Integer = 0 to integer.Max Next ' return the result... Return result End Function My Questions: If I have two or more threads in the same vb .net app and each of them calls the shared function at the same time with different RADIUS, will they each get their own AREA? I want to know for each call to the function if it is using same local variables or each call creates new instances of local variables? Will the answers to above questions be same If I have multiple (2+) single threaded apps and they all call the function at the same time with different RADIUS value? I will appreciate your reponse. Thank you.

    Read the article

  • Slight confusion of `this` in a JavaScript call back function

    - by thecoshman
    $.ajax({url: path_to_file, cache: false, success: function(html_result){ $("#window_" + this.id + "_cont_buffer").html(html_result);}) Now then. This function call is with in a function of a class. this.id is a property of said class. will this pass the function value of this.id into the string the anonymous function, or will it try to evaluate it when the function actually gets called, thus making no sense. If this is not going to work how I want it to, can you recommend how I achieve this.

    Read the article

  • jQuery function in .click() etc

    - by Martind
    Hi all. So normally, I do it like this: $('#selectRoom a').click( function(e) { e.preventDefault(); // To prevent the default behavior (following the link or adding # to URL) // Do some function specific logic here }); However, I would like to do it like this, to clean things up (and be able to reuse): $('#selectRoom a').click( selectRoom ); function selectRoom () { e.preventDefault(); // To prevent the default behavior (following the link or adding # to URL) // Do some function specific logic here } The problem is, i cant pass the "e" event-handler to the function, then the selectRoom() function is called on load. i.e: $('#selectRoom a').click( selectRoom(e) ); Can I fix this somehow?

    Read the article

  • jQuery plugin call internal function

    - by pbcoder
    I want to call removeSomething() (see in line 9) internally: JS-Code is: (function($){ $.fn.extend({ Engine: function(options) { var defaults = { ... }; var options = $.extend(defaults, options); removeSomething(); //----------------------------------------------------------------------- //Public Functions ------------------------------------------------------ //----------------------------------------------------------------------- this.removeSomething = function() { ... }; } }); })(jQuery); But if I call removeSomething console outputs that removeSomething is not a function, how do I have to call this function? The function should be available internally and externally. Thanks for help!

    Read the article

  • How can pointers to functions point to something that doesn't exist in memory yet? Why do prototypes have different addresses?

    - by Kacy Raye
    To my knowledge, functions do not get added to the stack until run-time after they are called in the main function. So how can a pointer to a function have a function's memory address if it doesn't exist in memory? For example: using namespace std; #include <iostream> void func() { } int main() { void (*ptr)() = func; cout << reinterpret_cast<void*>(ptr) << endl; //prints 0x8048644 even though func never gets added to the stack } Also, this next question is a little less important to me, so if you only know the answer to my first question, then that is fine. But anyway, why does the value of the pointer ( the memory address of the function ) differ when I declare a function prototype and implement the function after main? In the first example, it printed out 0x8048644 no matter how many times I ran the program. In the next example, it printed out 0x8048680 no matter how many times I ran the program. For example: using namespace std; #include <iostream> void func(); int main() { void ( *ptr )() = func; cout << reinterpret_cast<void*>(ptr) << endl; } void func(){ }

    Read the article

  • Intermittent PHP error: Undefined function <core function>

    - by Daniel
    In the last week I've been coming across an incredibly annoying error on one of Slicehost slices. It appears that every now and then PHP will fail with a fatal error, saying a certain function is undefined. The function changes, but is always a core PHP function e.g. defined(), version_compare(), etc. This problem has occurred while using several different PHP applications - PHPMyAdmin, my own custom built apps, etc, leading me to believe that the problem is not specific to the running code. Here are some details: - Debian Lenny - Apache 2.2.9 - PHP 5.2.6-1+lenny4 with Suhosin-Patch (running eAccelerator 0.9.6) Apache and PHP are installed from Debian packages. Error logs show nothing out of the ordinary. I thought memory might be an issue, but free -m reports upwards of 100MB free almost all the time. Another thing I'm trying to investigate is if the problem might be related to eAccelerator, but testing this theory out is incredibly hard because the issue doesn't appear very often and I've been using eAccelerator for months on this install without any problems up until now. Has anyone ever come across anything like this? Why would PHP report undefined core functions?

    Read the article

  • Metro: Creating an IndexedDbDataSource for WinJS

    - by Stephen.Walther
    The goal of this blog entry is to describe how you can create custom data sources which you can use with the controls in the WinJS library. In particular, I explain how you can create an IndexedDbDataSource which you can use to store and retrieve data from an IndexedDB database. If you want to skip ahead, and ignore all of the fascinating content in-between, I’ve included the complete code for the IndexedDbDataSource at the very bottom of this blog entry. What is IndexedDB? IndexedDB is a database in the browser. You can use the IndexedDB API with all modern browsers including Firefox, Chrome, and Internet Explorer 10. And, of course, you can use IndexedDB with Metro style apps written with JavaScript. If you need to persist data in a Metro style app written with JavaScript then IndexedDB is a good option. Each Metro app can only interact with its own IndexedDB databases. And, IndexedDB provides you with transactions, indices, and cursors – the elements of any modern database. An IndexedDB database might be different than the type of database that you normally use. An IndexedDB database is an object-oriented database and not a relational database. Instead of storing data in tables, you store data in object stores. You store JavaScript objects in an IndexedDB object store. You create new IndexedDB object stores by handling the upgradeneeded event when you attempt to open a connection to an IndexedDB database. For example, here’s how you would both open a connection to an existing database named TasksDB and create the TasksDB database when it does not already exist: var reqOpen = window.indexedDB.open(“TasksDB”, 2); reqOpen.onupgradeneeded = function (evt) { var newDB = evt.target.result; newDB.createObjectStore("tasks", { keyPath: "id", autoIncrement: true }); }; reqOpen.onsuccess = function () { var db = reqOpen.result; // Do something with db }; When you call window.indexedDB.open(), and the database does not already exist, then the upgradeneeded event is raised. In the code above, the upgradeneeded handler creates a new object store named tasks. The new object store has an auto-increment column named id which acts as the primary key column. If the database already exists with the right version, and you call window.indexedDB.open(), then the success event is raised. At that point, you have an open connection to the existing database and you can start doing something with the database. You use asynchronous methods to interact with an IndexedDB database. For example, the following code illustrates how you would add a new object to the tasks object store: var transaction = db.transaction(“tasks”, “readwrite”); var reqAdd = transaction.objectStore(“tasks”).add({ name: “Feed the dog” }); reqAdd.onsuccess = function() { // Tasks added successfully }; The code above creates a new database transaction, adds a new task to the tasks object store, and handles the success event. If the new task gets added successfully then the success event is raised. Creating a WinJS IndexedDbDataSource The most powerful control in the WinJS library is the ListView control. This is the control that you use to display a collection of items. If you want to display data with a ListView control, you need to bind the control to a data source. The WinJS library includes two objects which you can use as a data source: the List object and the StorageDataSource object. The List object enables you to represent a JavaScript array as a data source and the StorageDataSource enables you to represent the file system as a data source. If you want to bind an IndexedDB database to a ListView then you have a choice. You can either dump the items from the IndexedDB database into a List object or you can create a custom data source. I explored the first approach in a previous blog entry. In this blog entry, I explain how you can create a custom IndexedDB data source. Implementing the IListDataSource Interface You create a custom data source by implementing the IListDataSource interface. This interface contains the contract for the methods which the ListView needs to interact with a data source. The easiest way to implement the IListDataSource interface is to derive a new object from the base VirtualizedDataSource object. The VirtualizedDataSource object requires a data adapter which implements the IListDataAdapter interface. Yes, because of the number of objects involved, this is a little confusing. Your code ends up looking something like this: var IndexedDbDataSource = WinJS.Class.derive( WinJS.UI.VirtualizedDataSource, function (dbName, dbVersion, objectStoreName, upgrade, error) { this._adapter = new IndexedDbDataAdapter(dbName, dbVersion, objectStoreName, upgrade, error); this._baseDataSourceConstructor(this._adapter); }, { nuke: function () { this._adapter.nuke(); }, remove: function (key) { this._adapter.removeInternal(key); } } ); The code above is used to create a new class named IndexedDbDataSource which derives from the base VirtualizedDataSource class. In the constructor for the new class, the base class _baseDataSourceConstructor() method is called. A data adapter is passed to the _baseDataSourceConstructor() method. The code above creates a new method exposed by the IndexedDbDataSource named nuke(). The nuke() method deletes all of the objects from an object store. The code above also overrides a method named remove(). Our derived remove() method accepts any type of key and removes the matching item from the object store. Almost all of the work of creating a custom data source goes into building the data adapter class. The data adapter class implements the IListDataAdapter interface which contains the following methods: · change() · getCount() · insertAfter() · insertAtEnd() · insertAtStart() · insertBefore() · itemsFromDescription() · itemsFromEnd() · itemsFromIndex() · itemsFromKey() · itemsFromStart() · itemSignature() · moveAfter() · moveBefore() · moveToEnd() · moveToStart() · remove() · setNotificationHandler() · compareByIdentity Fortunately, you are not required to implement all of these methods. You only need to implement the methods that you actually need. In the case of the IndexedDbDataSource, I implemented the getCount(), itemsFromIndex(), insertAtEnd(), and remove() methods. If you are creating a read-only data source then you really only need to implement the getCount() and itemsFromIndex() methods. Implementing the getCount() Method The getCount() method returns the total number of items from the data source. So, if you are storing 10,000 items in an object store then this method would return the value 10,000. Here’s how I implemented the getCount() method: getCount: function () { var that = this; return new WinJS.Promise(function (complete, error) { that._getObjectStore().then(function (store) { var reqCount = store.count(); reqCount.onerror = that._error; reqCount.onsuccess = function (evt) { complete(evt.target.result); }; }); }); } The first thing that you should notice is that the getCount() method returns a WinJS promise. This is a requirement. The getCount() method is asynchronous which is a good thing because all of the IndexedDB methods (at least the methods implemented in current browsers) are also asynchronous. The code above retrieves an object store and then uses the IndexedDB count() method to get a count of the items in the object store. The value is returned from the promise by calling complete(). Implementing the itemsFromIndex method When a ListView displays its items, it calls the itemsFromIndex() method. By default, it calls this method multiple times to get different ranges of items. Three parameters are passed to the itemsFromIndex() method: the requestIndex, countBefore, and countAfter parameters. The requestIndex indicates the index of the item from the database to show. The countBefore and countAfter parameters represent hints. These are integer values which represent the number of items before and after the requestIndex to retrieve. Again, these are only hints and you can return as many items before and after the request index as you please. Here’s how I implemented the itemsFromIndex method: itemsFromIndex: function (requestIndex, countBefore, countAfter) { var that = this; return new WinJS.Promise(function (complete, error) { that.getCount().then(function (count) { if (requestIndex >= count) { return WinJS.Promise.wrapError(new WinJS.ErrorFromName(WinJS.UI.FetchError.doesNotExist)); } var startIndex = Math.max(0, requestIndex - countBefore); var endIndex = Math.min(count, requestIndex + countAfter + 1); that._getObjectStore().then(function (store) { var index = 0; var items = []; var req = store.openCursor(); req.onerror = that._error; req.onsuccess = function (evt) { var cursor = evt.target.result; if (index < startIndex) { index = startIndex; cursor.advance(startIndex); return; } if (cursor && index < endIndex) { index++; items.push({ key: cursor.value[store.keyPath].toString(), data: cursor.value }); cursor.continue(); return; } results = { items: items, offset: requestIndex - startIndex, totalCount: count }; complete(results); }; }); }); }); } In the code above, a cursor is used to iterate through the objects in an object store. You fetch the next item in the cursor by calling either the cursor.continue() or cursor.advance() method. The continue() method moves forward by one object and the advance() method moves forward a specified number of objects. Each time you call continue() or advance(), the success event is raised again. If the cursor is null then you know that you have reached the end of the cursor and you can return the results. Some things to be careful about here. First, the return value from the itemsFromIndex() method must implement the IFetchResult interface. In particular, you must return an object which has an items, offset, and totalCount property. Second, each item in the items array must implement the IListItem interface. Each item should have a key and a data property. Implementing the insertAtEnd() Method When creating the IndexedDbDataSource, I wanted to go beyond creating a simple read-only data source and support inserting and deleting objects. If you want to support adding new items with your data source then you need to implement the insertAtEnd() method. Here’s how I implemented the insertAtEnd() method for the IndexedDbDataSource: insertAtEnd:function(unused, data) { var that = this; return new WinJS.Promise(function (complete, error) { that._getObjectStore("readwrite").done(function(store) { var reqAdd = store.add(data); reqAdd.onerror = that._error; reqAdd.onsuccess = function (evt) { var reqGet = store.get(evt.target.result); reqGet.onerror = that._error; reqGet.onsuccess = function (evt) { var newItem = { key:evt.target.result[store.keyPath].toString(), data:evt.target.result } complete(newItem); }; }; }); }); } When implementing the insertAtEnd() method, you need to be careful to return an object which implements the IItem interface. In particular, you should return an object that has a key and a data property. The key must be a string and it uniquely represents the new item added to the data source. The value of the data property represents the new item itself. Implementing the remove() Method Finally, you use the remove() method to remove an item from the data source. You call the remove() method with the key of the item which you want to remove. Implementing the remove() method in the case of the IndexedDbDataSource was a little tricky. The problem is that an IndexedDB object store uses an integer key and the VirtualizedDataSource requires a string key. For that reason, I needed to override the remove() method in the derived IndexedDbDataSource class like this: var IndexedDbDataSource = WinJS.Class.derive( WinJS.UI.VirtualizedDataSource, function (dbName, dbVersion, objectStoreName, upgrade, error) { this._adapter = new IndexedDbDataAdapter(dbName, dbVersion, objectStoreName, upgrade, error); this._baseDataSourceConstructor(this._adapter); }, { nuke: function () { this._adapter.nuke(); }, remove: function (key) { this._adapter.removeInternal(key); } } ); When you call remove(), you end up calling a method of the IndexedDbDataAdapter named removeInternal() . Here’s what the removeInternal() method looks like: setNotificationHandler: function (notificationHandler) { this._notificationHandler = notificationHandler; }, removeInternal: function(key) { var that = this; return new WinJS.Promise(function (complete, error) { that._getObjectStore("readwrite").done(function (store) { var reqDelete = store.delete (key); reqDelete.onerror = that._error; reqDelete.onsuccess = function (evt) { that._notificationHandler.removed(key.toString()); complete(); }; }); }); } The removeInternal() method calls the IndexedDB delete() method to delete an item from the object store. If the item is deleted successfully then the _notificationHandler.remove() method is called. Because we are not implementing the standard IListDataAdapter remove() method, we need to notify the data source (and the ListView control bound to the data source) that an item has been removed. The way that you notify the data source is by calling the _notificationHandler.remove() method. Notice that we get the _notificationHandler in the code above by implementing another method in the IListDataAdapter interface: the setNotificationHandler() method. You can raise the following types of notifications using the _notificationHandler: · beginNotifications() · changed() · endNotifications() · inserted() · invalidateAll() · moved() · removed() · reload() These methods are all part of the IListDataNotificationHandler interface in the WinJS library. Implementing the nuke() Method I wanted to implement a method which would remove all of the items from an object store. Therefore, I created a method named nuke() which calls the IndexedDB clear() method: nuke: function () { var that = this; return new WinJS.Promise(function (complete, error) { that._getObjectStore("readwrite").done(function (store) { var reqClear = store.clear(); reqClear.onerror = that._error; reqClear.onsuccess = function (evt) { that._notificationHandler.reload(); complete(); }; }); }); } Notice that the nuke() method calls the _notificationHandler.reload() method to notify the ListView to reload all of the items from its data source. Because we are implementing a custom method here, we need to use the _notificationHandler to send an update. Using the IndexedDbDataSource To illustrate how you can use the IndexedDbDataSource, I created a simple task list app. You can add new tasks, delete existing tasks, and nuke all of the tasks. You delete an item by selecting an item (swipe or right-click) and clicking the Delete button. Here’s the HTML page which contains the ListView, the form for adding new tasks, and the buttons for deleting and nuking tasks: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>DataSources</title> <!-- WinJS references --> <link href="//Microsoft.WinJS.1.0.RC/css/ui-dark.css" rel="stylesheet" /> <script src="//Microsoft.WinJS.1.0.RC/js/base.js"></script> <script src="//Microsoft.WinJS.1.0.RC/js/ui.js"></script> <!-- DataSources references --> <link href="indexedDb.css" rel="stylesheet" /> <script type="text/javascript" src="indexedDbDataSource.js"></script> <script src="indexedDb.js"></script> </head> <body> <div id="tmplTask" data-win-control="WinJS.Binding.Template"> <div class="taskItem"> Id: <span data-win-bind="innerText:id"></span> <br /><br /> Name: <span data-win-bind="innerText:name"></span> </div> </div> <div id="lvTasks" data-win-control="WinJS.UI.ListView" data-win-options="{ itemTemplate: select('#tmplTask'), selectionMode: 'single' }"></div> <form id="frmAdd"> <fieldset> <legend>Add Task</legend> <label>New Task</label> <input id="inputTaskName" required /> <button>Add</button> </fieldset> </form> <button id="btnNuke">Nuke</button> <button id="btnDelete">Delete</button> </body> </html> And here is the JavaScript code for the TaskList app: /// <reference path="//Microsoft.WinJS.1.0.RC/js/base.js" /> /// <reference path="//Microsoft.WinJS.1.0.RC/js/ui.js" /> function init() { WinJS.UI.processAll().done(function () { var lvTasks = document.getElementById("lvTasks").winControl; // Bind the ListView to its data source var tasksDataSource = new DataSources.IndexedDbDataSource("TasksDB", 1, "tasks", upgrade); lvTasks.itemDataSource = tasksDataSource; // Wire-up Add, Delete, Nuke buttons document.getElementById("frmAdd").addEventListener("submit", function (evt) { evt.preventDefault(); tasksDataSource.beginEdits(); tasksDataSource.insertAtEnd(null, { name: document.getElementById("inputTaskName").value }).done(function (newItem) { tasksDataSource.endEdits(); document.getElementById("frmAdd").reset(); lvTasks.ensureVisible(newItem.index); }); }); document.getElementById("btnDelete").addEventListener("click", function () { if (lvTasks.selection.count() == 1) { lvTasks.selection.getItems().done(function (items) { tasksDataSource.remove(items[0].data.id); }); } }); document.getElementById("btnNuke").addEventListener("click", function () { tasksDataSource.nuke(); }); // This method is called to initialize the IndexedDb database function upgrade(evt) { var newDB = evt.target.result; newDB.createObjectStore("tasks", { keyPath: "id", autoIncrement: true }); } }); } document.addEventListener("DOMContentLoaded", init); The IndexedDbDataSource is created and bound to the ListView control with the following two lines of code: var tasksDataSource = new DataSources.IndexedDbDataSource("TasksDB", 1, "tasks", upgrade); lvTasks.itemDataSource = tasksDataSource; The IndexedDbDataSource is created with four parameters: the name of the database to create, the version of the database to create, the name of the object store to create, and a function which contains code to initialize the new database. The upgrade function creates a new object store named tasks with an auto-increment property named id: function upgrade(evt) { var newDB = evt.target.result; newDB.createObjectStore("tasks", { keyPath: "id", autoIncrement: true }); } The Complete Code for the IndexedDbDataSource Here’s the complete code for the IndexedDbDataSource: (function () { /************************************************ * The IndexedDBDataAdapter enables you to work * with a HTML5 IndexedDB database. *************************************************/ var IndexedDbDataAdapter = WinJS.Class.define( function (dbName, dbVersion, objectStoreName, upgrade, error) { this._dbName = dbName; // database name this._dbVersion = dbVersion; // database version this._objectStoreName = objectStoreName; // object store name this._upgrade = upgrade; // database upgrade script this._error = error || function (evt) { console.log(evt.message); }; }, { /******************************************* * IListDataAdapter Interface Methods ********************************************/ getCount: function () { var that = this; return new WinJS.Promise(function (complete, error) { that._getObjectStore().then(function (store) { var reqCount = store.count(); reqCount.onerror = that._error; reqCount.onsuccess = function (evt) { complete(evt.target.result); }; }); }); }, itemsFromIndex: function (requestIndex, countBefore, countAfter) { var that = this; return new WinJS.Promise(function (complete, error) { that.getCount().then(function (count) { if (requestIndex >= count) { return WinJS.Promise.wrapError(new WinJS.ErrorFromName(WinJS.UI.FetchError.doesNotExist)); } var startIndex = Math.max(0, requestIndex - countBefore); var endIndex = Math.min(count, requestIndex + countAfter + 1); that._getObjectStore().then(function (store) { var index = 0; var items = []; var req = store.openCursor(); req.onerror = that._error; req.onsuccess = function (evt) { var cursor = evt.target.result; if (index < startIndex) { index = startIndex; cursor.advance(startIndex); return; } if (cursor && index < endIndex) { index++; items.push({ key: cursor.value[store.keyPath].toString(), data: cursor.value }); cursor.continue(); return; } results = { items: items, offset: requestIndex - startIndex, totalCount: count }; complete(results); }; }); }); }); }, insertAtEnd:function(unused, data) { var that = this; return new WinJS.Promise(function (complete, error) { that._getObjectStore("readwrite").done(function(store) { var reqAdd = store.add(data); reqAdd.onerror = that._error; reqAdd.onsuccess = function (evt) { var reqGet = store.get(evt.target.result); reqGet.onerror = that._error; reqGet.onsuccess = function (evt) { var newItem = { key:evt.target.result[store.keyPath].toString(), data:evt.target.result } complete(newItem); }; }; }); }); }, setNotificationHandler: function (notificationHandler) { this._notificationHandler = notificationHandler; }, /***************************************** * IndexedDbDataSource Method ******************************************/ removeInternal: function(key) { var that = this; return new WinJS.Promise(function (complete, error) { that._getObjectStore("readwrite").done(function (store) { var reqDelete = store.delete (key); reqDelete.onerror = that._error; reqDelete.onsuccess = function (evt) { that._notificationHandler.removed(key.toString()); complete(); }; }); }); }, nuke: function () { var that = this; return new WinJS.Promise(function (complete, error) { that._getObjectStore("readwrite").done(function (store) { var reqClear = store.clear(); reqClear.onerror = that._error; reqClear.onsuccess = function (evt) { that._notificationHandler.reload(); complete(); }; }); }); }, /******************************************* * Private Methods ********************************************/ _ensureDbOpen: function () { var that = this; // Try to get cached Db if (that._cachedDb) { return WinJS.Promise.wrap(that._cachedDb); } // Otherwise, open the database return new WinJS.Promise(function (complete, error, progress) { var reqOpen = window.indexedDB.open(that._dbName, that._dbVersion); reqOpen.onerror = function (evt) { error(); }; reqOpen.onupgradeneeded = function (evt) { that._upgrade(evt); that._notificationHandler.invalidateAll(); }; reqOpen.onsuccess = function () { that._cachedDb = reqOpen.result; complete(that._cachedDb); }; }); }, _getObjectStore: function (type) { type = type || "readonly"; var that = this; return new WinJS.Promise(function (complete, error) { that._ensureDbOpen().then(function (db) { var transaction = db.transaction(that._objectStoreName, type); complete(transaction.objectStore(that._objectStoreName)); }); }); }, _get: function (key) { return new WinJS.Promise(function (complete, error) { that._getObjectStore().done(function (store) { var reqGet = store.get(key); reqGet.onerror = that._error; reqGet.onsuccess = function (item) { complete(item); }; }); }); } } ); var IndexedDbDataSource = WinJS.Class.derive( WinJS.UI.VirtualizedDataSource, function (dbName, dbVersion, objectStoreName, upgrade, error) { this._adapter = new IndexedDbDataAdapter(dbName, dbVersion, objectStoreName, upgrade, error); this._baseDataSourceConstructor(this._adapter); }, { nuke: function () { this._adapter.nuke(); }, remove: function (key) { this._adapter.removeInternal(key); } } ); WinJS.Namespace.define("DataSources", { IndexedDbDataSource: IndexedDbDataSource }); })(); Summary In this blog post, I provided an overview of how you can create a new data source which you can use with the WinJS library. I described how you can create an IndexedDbDataSource which you can use to bind a ListView control to an IndexedDB database. While describing how you can create a custom data source, I explained how you can implement the IListDataAdapter interface. You also learned how to raise notifications — such as a removed or invalidateAll notification — by taking advantage of the methods of the IListDataNotificationHandler interface.

    Read the article

  • IF function that refers to another cell if true

    - by geoconfusion
    Can someone please help? I am using the IF function to find cells within certain ranges, but want the cell to contain the value if it falls within that specific range. for example: =IF (AA3 is between 150 and 400 then AD3 is equal to AA3 and if not leave blank) my current formula below does not work: =IF(AND(AA3150, AA3<400), AD3=AA3, "" ) where AD3 is the cell I am working in... any suggestions?

    Read the article

  • vba function, return from function

    - by Mike
    I don't normally use VB, and even less vba for excel, but I'm writing a function inside a macro and seem to not understand even the basics of creating a function For example Public Function test() As Integer return 1 End Function This gives a compile error. This is profoundly stupid, but how do I make a function return an integer in vba?

    Read the article

  • boost::function function pointer to parameters?

    - by high6
    How does boost::function take a function pointer and get parameters from it? I want wrap a function pointer so that it can be validated before being called. And it would be nice to be able to call it like boost::function is with the () operator and not having to access the function pointer member. Wrapper func; func(5); //Yes :D func.Ptr(5) //Easy to do, but not as nice looking

    Read the article

  • jQuery - how to repeat a function within itself to include nested files

    - by brandonjp
    I'm not sure what to call this question, since it involves a variety of things, but we'll start with the first issue... I've been trying to write a simple to use jQuery for includes (similar to php or ssi) on static html sites. Whenever it finds div.jqinclude it gets attr('title') (which is my external html file), then uses load() to include the external html file. Afterwards it changes the class of the div to jqincluded So my main index.html might contain several lines like so: <div class="jqinclude" title="menu.html"></div> However, within menu.html there might be other includes nested. So it needs to make the first level of includes, then perform the same action on the newly included content. So far it works fine, but it's very verbose and only goes a couple levels deep. How would I make the following repeated function to continually loop until no more class="jqinclude" elements are left on the page? I've tried arguments.callee and some other convoluted wacky attempts to no avail. I'm also interested to know if there's another completely different way I should be doing this. $('div.jqinclude').each(function() { // begin repeat here var file = $(this).attr('title'); $(this).load(file, function() { $(this).removeClass('jqinclude').addClass('jqincluded'); $(this).find('div.jqinclude').each(function() { // end repeat here var file = $(this).attr('title'); $(this).load(file, function() { $(this).removeClass('jqinclude').addClass('jqincluded'); $(this).find('div.jqinclude').each(function() { var file = $(this).attr('title'); $(this).load(file, function() { $(this).removeClass('jqinclude').addClass('jqincluded'); }); }); }); }); }); });

    Read the article

  • fortran complications passing arrays in function

    - by user1514188
    I'm trying to write a program to calculate a cross product of two vectors (input is of "real" type, so for example [1.3 3.4 1,5]). But I keep getting numerous errors: program Q3CW implicit none REAL :: matA(3), matB(3) REAL :: A11, A12, A13 REAL :: B11, B12, B13 real :: productc(3), answer(3) read*,A11, A12, A13 read*,B11, B12, B13 matA = (/A11, A12, A13/) matB = (/B11, B12, B13/) answer = productc(matA, matB) print*,'Answer = ', answer(1), answer(2), answer(3) end program real function productc(matIn1, matIn2) real, dimension(3) :: matIn1, matIn2 productc(1)=(/matIn1(2)*matIn2(3)-matIn1(3)*matIn2(2)/) productc(2)=(/matIn1(3)*matIn2(1)-matIn1(1)*matIn2(3)/) productc(3)=(/matIn1(1)*matIn2(2)-matIn1(2)*matIn2(1)/) end function This is the error I get: Error: Q33333.f95(20) : Statement function definition for pre-existing procedure PRODUCTC; detected at )@= Error: Q33333.f95(21) : Statement function definition for pre-existing procedure PRODUCTC; detected at )@= Error: Q33333.f95(22) : Statement function definition for pre-existing procedure PRODUCTC; detected at )@= Warning: Q33333.f95(23) : Function PRODUCTC has not been assigned a value; detected at FUNCTION@<end-of-statement> Build Result Error(3) Warning(1) Extension(0) Any idea what the problem could be ?

    Read the article

  • Calling function after .load (Jquery)

    - by Matt
    Having a little difficulty getting a function to call after a .load: $(function(){ $('a.pageFetcher').click(function(){ $('#main').load($(this).attr('rel')); }); }); The page loads, but the functions don't fire: $(function(){ var $container = $('#container'); $container.imagesLoaded(function(){ $container.masonry({ itemSelector: '.box', }); }); $container.infinitescroll({ navSelector : '#page-nav', nextSelector : '#page-nav a', itemSelector : '.box', loading: { finishedMsg: 'Nothing else to load.', img: 'http://i.imgur.com/6RMhx.gif' } }, function( newElements ) { $.superbox.settings = { closeTxt: "Close this", loadTxt: "Loading your selection", nextTxt: "Next item", prevTxt: "Previous item" }; $.superbox(); var $newElems = $( newElements ).css({ opacity: 0 }); $newElems.imagesLoaded(function(){ $newElems.animate({ opacity: 1 }); $container.masonry( 'appended', $newElems, true ); }); } ); }); I've attempted to combine them so that the 2nd functions are called after .load (after doing some searching on this site and looking at given answers/examples) but nothing seems to work properly. Suggestions?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >