Search Results

Search found 194 results on 8 pages for 'splice'.

Page 8/8 | < Previous Page | 4 5 6 7 8 

  • More efficient comparison of numbers

    - by Pez Cuckow
    I have an array which is part of a small JS game I am working on I need to check (as often as reasonable) that each of the elements in the array haven't left the "stage" or "playground", so I can remove them and save the script load I have coded the below and was wondering if anyone knew a faster/more efficient way to calculate this. This is run every 50ms (it deals with the movement). Where bots[i][1] is movement in X and bots[i][2] is movement in Y (mutually exclusive). for (var i in bots) { var left = parseInt($("#" + i).css("left")); var top = parseInt($("#" + i).css("top")); var nextleft = left + bots[i][1]; var nexttop = top + bots[i][2]; if(bots[i][1]>0&&nextleft>=PLAYGROUND_WIDTH) { remove_bot(i); } else if(bots[i][1]<0&&nextleft<=-GRID_SIZE) { remove_bot(i); } else if(bots[i][2]>0&&nexttop>=PLAYGROUND_HEIGHT) { remove_bot(i); } else if(bots[i][2]<0&&nexttop<=-GRID_SIZE) { remove_bot(i); } else { //alert(nextleft + ":" + nexttop); $("#" + i).css("left", ""+(nextleft)+"px"); $("#" + i).css("top", ""+(nexttop)+"px"); } } On a similar note the remove_bot(i); function is as below, is this correct (I can't splice as it changes all the ID's of the elements in the array. function remove_bot(i) { $("#" + i).remove(); bots[i] = false; } Many thanks for any advice given!

    Read the article

  • delete row from result set in web sql with javascript

    - by Kaijin
    I understand that the result set from web sql isn't quite an array, more of an object? I'm cycling through a result set and to speed things up I'd like to remove a row once it's been found. I've tried "delete" and "splice", the former does nothing and the latter throws an error. Here's a piece of what I'm trying to do, notice the delete on line 18: function selectFromReverse(reverseRay,suggRay){ var reverseString = reverseRay.toString(); db.transaction(function (tx) { tx.executeSql('SELECT votecount, comboid FROM counterCombos WHERE comboid IN ('+reverseString+') AND votecount>0', [], function(tx, results){ processSelectFromReverse(results,suggRay); }); }, function(){onError}); } function processSelectFromReverse(results,suggRay){ var i = suggRay.length; while(i--){ var j = results.rows.length; while(j--){ console.log('searching'); var found = 0; if(suggRay[i].reverse == results.rows.item(j).comboid){ delete results.rows.item(j); console.log('found'); found++; break; } } if(found == 0){ console.log('lost'); } } }

    Read the article

  • Array, change color, as3

    - by pixelGreaser
    Hi Thanks for the help Yesterday, but I have on more question. How can I change color of text on certain words? My animation plays the text animation of THIS SALE IS RED HOT!!! I want RED HOT it to be red. It seems the array can be indexed in such a way to switch the color from Blue to Red. MY BANNER ADD var myArray:Array = ["THIS","SALE","IS","RED HOT!!!",]; var tm:Timer = new Timer(500); tm.addEventListener(TimerEvent.TIMER, countdown); function countdown(event:TimerEvent) { tx.text = myArray[(tm.currentCount-1)%myArray.length]; } tm.start(); tx.textColor = 0x0000FF; Cont...PSEUDO CODE //var myArray:Array = ["This","Sale","is","RED HOT!!!",]; var spliceRedhot = myArray.splice(-1); //trace(myArray[2]); trace(spliceRedhot); function mySplice(e:Event):void{ if (spliceRedhot = 4){ //Make RED HOT!!! red tx.textColor = 0xFF0000; } else{ //Text is Blue again tx.textColor = 0x0000FF; } }

    Read the article

  • In jQuery datepicker beforeShowDay if fails

    - by michalzuber
    HI. I'm having problem to highlight more days. Somehow the if statement in beforeShowDay isn't true when it should be :( dateString typeof is string and an example is available in the screenshot at http://mikaelz.host.sk/datepicker.png Pasted code: var dates = new Array(); function addDate(date) {if (jQuery.inArray(date, dates) < 0) dates.push(date);} function removeDate(index) {dates.splice(index, 1);} function addOrRemoveDate(date) { var index = jQuery.inArray(date, dates); if (index >= 0) removeDate(index); else addDate(date); } function padNumber(number) { var ret = new String(number); if (ret.length == 1) ret = "0" + ret; return ret; } jQuery(document).ready(function(){ jQuery("#pick-date").datepicker({ onSelect: function(dateText, inst) { addOrRemoveDate(dateText); }, beforeShowDay: function (date){ var year = date.getFullYear(); var month = padNumber(date.getMonth()); var day = padNumber(date.getDate()); var dateString = day + "." + month + "." + year; if (dates.indexOf(dateString) >= 0) { return [true,"ui-state-highlight"]; } return [true, ""]; } }); }); Big thanks for any good ideas what could be wrong.

    Read the article

  • How to add an array value to the middle of an associative array?

    - by Citizen
    Lets say I have this array: $array = array('a'=>1,'z'=>2,'d'=>4); Later in the script, I want to add the value 'c'=>3 before 'z'. How can I do this? EDIT: Yes, the order is important. When I run a foreach() through the array, I do NOT want this newly added value added to the end of the array. I am getting this array from a mysql_fetch_assoc() EDIT 2: The keys I used above are placeholders. Using ksort() will not achieve what I want. EDIT 3: http://www.php.net/manual/en/function.array-splice.php#88896 accomplishes what I'm looking for but I'm looking for something simpler. EDIT 4: Thanks for the downvotes. I gave feedback to your answers and you couldn't help, so you downvoted and requested to close the question because you didn't know the answer. Thanks. EDIT 5: Take a sample db table with about 30 columns. I get this data using mysql_fetch_assoc(). In this new array, after column 'pizza' and 'drink', I want to add a new column 'full_dinner' that combines the values of 'pizza' and 'drink' so that when I run a foreach() on the said array, 'full_dinner' comes directly after 'drink'

    Read the article

  • Sort ranges in an array in google apps script

    - by user1637113
    I have a timesheet spreadsheet for our company and I need to sort the employees by each timesheet block (15 rows by 20 columns). I have the following code which I had help with, but the array quits sorting once it comes to a block without an employee name (I would like these to be shuffled to the bottom). Another complication I am having is there are numerous formulas in these cells and when I run it as is, it removes them. I would like to keep these intact if at all possible. Here's the code: function sortSections() { var activeSheet = SpreadsheetApp.getActiveSheet(); //SETTINGS var sheetName = activeSheet.getSheetName(); //name of sheet to be sorted var headerRows = 53; //number of header rows var pageHeaderRows = 5; //page totals to top of next emp section var sortColumn = 11; //index of column to be sorted by; 1 = column A var pageSize = 65; var sectionSize = 15; //number of rows in each section var col = sortColumn-1; var sheet = SpreadsheetApp.getActive().getSheetByName(sheetName); var data = sheet.getRange(headerRows+1, 1, sheet.getMaxRows()-headerRows, sheet.getLastColumn()).getValues(); var data3d = []; var dataLength = data.length/sectionSize; for (var i = 0; i < dataLength; i++) { data3d[i] = data.splice(0, sectionSize); } data3d.sort(function(a,b){return(((a[0][col]<b[0][col])&&a[0][col])?-1:((a[0][col]>b[0][col])?1:0))}); var sortedData = []; for (var k in data3d) { for (var l in data3d[k]) { sortedData.push(data3d[k][l]); } } sheet.getRange(headerRows+1, 1, sortedData.length, sortedData[0].length).setValues(sortedData);

    Read the article

  • Javascript indexOf() always returns -1

    - by Thomas
    I try to retrieve the index of en element in an array. This works perfectly var onCreate = function (event) { console.assert(markers[markerId] === undefined); var markerId = event.markerId; markers[markerId] = {}; var marker = markers[markerId]; // create the container object marker.object3d = new THREE.Object3D(); marker.object3d.matrixAutoUpdate = false; scene.add(marker.object3d); //UPDATE ARRAY HOLDING CURRENT MARKERS console.log("ON CREATE"); console.log("current detected markers: " + currentMarkers); var idx = currentMarkers.indexOf(markerId); // Find the index console.log("marker " + event.markerId + " has index: " + idx); if(idx==-1) // if does not exist currentMarkers.push(markerId); But this doesnt... var onDelete = function (event) { console.assert(markers[event.markerId] !== undefined); var markerId = event.markerId; //UPDATE ARRAY HOLDING CURRENT MARKERS console.log("ON DELETE"); console.log("current detected markers: " + currentMarkers); var idxx = currentMarkers.indexOf(markerId); // Find the index console.log("marker " + markerId + " has index: " + idxx); if(idxx != -1) {// if DOES exist currentMarkers.splice(idxx, 1); //Delete var idxxx = currentMarkersCoverChecked.indexOf(markerId); // Find the index if(idxxx == -1) // if does NOT exist, so if not being checked checkMarkerCovered(markerId); } onDeleteRandom(markerId); var marker = markers[markerId]; scene.remove(marker.object3d); delete markers[markerId]; Look at my console output: ON CREATE current detected markers: 2,1,4 marker 3 has index: -1 ON CREATE main.js:266 current detected markers: 2,1,4,3 marker 4 has index: 2 ON DELETE current detected markers: 2,1,4,3 marker 2 has index: -1 ON CREATE current detected markers: 2,1,4,3 marker 2 has index: 0 ON DELETE current detected markers: 2,1,4,3 marker 1 has index: -1

    Read the article

  • Prevent coersion to a single type in unlist() or c(); passing arguments to wrapper functions

    - by Leo Alekseyev
    Is there a simple way to flatten a list while retaining the original types of list constituents?.. Is there a way to programmatically construct a heterogeneous list?.. For instance, I want to create a simple wrapper for functions like png(filename,width,height) that would take device name, file name, and a list of options. The naive approach would be something like my.wrapper <- function(dev,name,opts) { do.call(dev,c(filename=name,opts)) } or similar code with unlist(list(...)). This doesn't work because opts gets coerced to character, and the resulting call is e.g. png(filename,width="500",height="500"). If there's no straightforward way to create heterogeneous lists like that, is there a standard idiomatic way to splice arguments into functions without naming them explicitly (e.g. do.call(dev,list(filename=name,width=opts["width"]))? -- Edit -- Gavin Simpson answered both questions below in his discussion about constructing wrapper functions. Let me give a summary of the answer to the title question: It is possible to construct a heterogeneous list with c() provided the arguments to c() are lists. To wit: > foo <- c("a","b"); bar <- 1:3 > c(foo,bar) [1] "a" "b" "1" "2" "3" > c(list(foo),list(bar)) [[1]] [1] "a" "b" [[2]] [1] 1 2 3 > c(as.list(foo),as.list(bar)) ## this creates a flattened heterogeneous list [[1]] [1] "a" [[2]] [1] "b" [[3]] [1] 1 [[4]] [1] 2 [[5]] [1] 3

    Read the article

  • jQuery UI portlets - toggle portlets to save to a cookie (half way there!)

    - by Gareth
    Hi, I'm a bit of a jQuery n00b so please excuse me if this seems like a stupid question. I am creating a site using the jQuery UI more specifically the sortable portlets. I have been able store whether or not a portlet is has been open or closed to a cookie. This is done using the following code. The slider ID is currently where the controls are stored to turn each portlet on and off. var cookie = $.cookie("hidden"); var hidden = cookie ? cookie.split("|").getUnique() : []; var cookieExpires = 7; // cookie expires in 7 days, or set this as a date object to specify a date // Remember content that was hidden $.each( hidden, function(){ var pid = this; //parseInt(this,10); $('#' + pid).hide(); $("#slider div[name='" + pid + "']").addClass('add'); }) // Add Click functionality $("#slider div").click(function(){ $(this).toggleClass('add'); var el = $("div#" + $(this).attr('name')); el.toggle(); updateCookie(el); }); $('a.toggle').click(function(){ $(this).parents(".portlet").hide(); // *** Below line just needs to select the correct 'id' and insert as selector i.e ('#slider div#block-1') and then update cookie! *** $('#slider div').addClass('add'); }); // Update the Cookie function updateCookie(el){ var indx = el.attr('id'); var tmp = hidden.getUnique(); if (el.is(':hidden')) { // add index of widget to hidden list tmp.push(indx); } else { // remove element id from the list tmp.splice( tmp.indexOf(indx) , 1); } hidden = tmp.getUnique(); $.cookie("hidden", hidden.join('|'), { expires: cookieExpires } ); } }) // Return a unique array. Array.prototype.getUnique = function() { var o = new Object(); var i, e; for (i = 0; e = this[i]; i++) {o[e] = 1}; var a = new Array(); for (e in o) {a.push (e)}; return a; } What I would like to do is also add a [x] into the corner of each portlet to give the user another way of hiding it but I'm unable to currently get this to store within the Cookie using the code above. Can anyone give me a pointer of how I would do this? Thanks in advance! Gareth

    Read the article

  • Seeking for faster $.(':data(key)')

    - by PoltoS
    I'm writing an extension to jQuery that adds data to DOM elements using el.data('lalala', my_data); and then uses that data to upload elements dynamically. Each time I get new data from the server I need to update all elements having el.data('lalala') != null; To get all needed elements I use an extension by James Padolsey: $(':data(lalala)').each(...); Everything was great until I came to the situation where I need to run that code 50 times - it is very slow! It takes about 8 seconds to execute on my page with 3640 DOM elements var x, t = (new Date).getTime(); for (n=0; n < 50; n++) { jQuery(':data(lalala)').each(function() { x++; }); }; console.log(((new Date).getTime()-t)/1000); Since I don't need RegExp as parameter of :data selector I've tried to replace this by var x, t = (new Date).getTime(); for (n=0; n < 50; n++) { jQuery('*').each(function() { if ($(this).data('lalala')) x++; }); }; console.log(((new Date).getTime()-t)/1000); This code is faster (5 sec), but I want get more. Q Are there any faster way to get all elements with this data key? In fact, I can keep an array with all elements I need, since I execute .data('key') in my module. Checking 100 elements having the desired .data('lalala') is better then checking 3640 :) So the solution would be like for (i in elements) { el = elements[i]; .... But sometimes elements are removed from the page (using jQuery .remove()). Both solutions described above [$(':data(lalala)') solution and if ($(this).data('lalala'))] will skip removed items (as I need), while the solution with array will still point to removed element (in fact, the element would not be really deleted - it will only be deleted from the DOM tree - because my array will still have a reference). I found that .remove() also removes data from the node, so my solution will change into var toRemove = []; for (vari in elements) { var el = elements[i]; if ($(el).data('lalala')) .... else toRemove.push(i); }; for (var ii in toRemove) elements.splice(toRemove[ii], 1); // remove element from array This solution is 100 times faster! Q Will the garbage collector release memory taken by DOM elements when deleted from that array? Remember, elements have been referenced by DOM tree, we made a new reference in our array, then removed with .remove() and then removed from the array. Is there a better way to do this?

    Read the article

  • Javascript phsyics in a 2d space

    - by eroo
    So, I am working on teaching myself Canvas (HTML5) and have most of a simple game engine coded up. It is a 2d representation of a space scene (planets, stars, celestial bodies, etc). My default "Sprite" class has a frame listener like such: "baseClass" contains a function that allows inheritance and applies "a" to "this.a". So, "var aTest = new Sprite({foo: 'bar'});" would make "aTest.foo = 'bar'". This is how I expose my objects to each other. { Sprite = baseClass.extend({ init: function(a){ baseClass.init(this, a); this.fields = new Array(); // list of fields of gravity one is in. Not sure if this is a good idea. this.addFL(function(tick){ // this will change to be independent of framerate soon. // and this is where I need help // gobjs is an array of all the Sprite objects in the "world". for(i = 0; i < gobjs.length; i++){ // Make sure its got setup correctly, make sure it -wants- gravity, and make sure it's not -this- sprite. if(typeof(gobjs[i].a) != undefined && !gobjs[i].a.ignoreGravity && gobjs[i].id != this.id){ // Check if it's within a certain range (obviously, gravity doesn't work this way... But I plan on having a large "space" area, // And I can't very well have all objects accounted for at all times, can I? if(this.distanceTo(gobjs[i]) < this.s.size*10 && gobjs[i].fields.indexOf(this.id) == -1){ gobjs[i].fields.push(this.id); } } } for(i = 0; i < this.fields.length; i++){ distance = this.distanceTo(gobjs[this.fields[i]]); angletosun = this.angleTo(gobjs[this.fields[i]])*(180/Math.PI); // .angleTo works very well, returning the angle in radians, which I convert to degrees here. // I have no idea what should happen here, although through trial and error (and attempting to read Maths papers on gravity (eeeeek!)), this sort of mimics gravity. // angle is its orientation, currently I assign a constant velocity to one of my objects, and leave the other static (it ignores gravity, but still emits it). this.a.angle = angletosun+(75+(distance*-1)/5); //todo: omg learn math if(this.distanceTo(gobjs[this.fields[i]]) > gobjs[this.fields[i]].a.size*10) this.fields.splice(i); // out of range, stop effecting. } }); } }); } Thanks in advance. The real trick is that one line: { this.a.angle = angletosun+(75+(distance*-1)/5); } This is more a physics question than Javascript, but I've searched and searched and read way to many wiki articles on orbital mathematics. It gets over my head very quickly. Edit: There is a weirdness with the SO formatting; forgives me, I is noobie.

    Read the article

  • CodePlex Daily Summary for Tuesday, May 22, 2012

    CodePlex Daily Summary for Tuesday, May 22, 2012Popular ReleasesBlackJumboDog: Ver5.6.3: 2012.05.22 Ver5.6.3  (1) HTTP????????、ftp://??????????????????????Internals Viewer (updated) for SQL Server 2008 R2.: Internals Viewer for SSMS 2008 R2: Updated code to work with SSMS 2008 R2. Changed dependancies, removing old assemblies no longer present and replacing them with updated versions.Orchard Project: Orchard 1.4.2: This is a service release to address 1.4 and 1.4.1 bugs. Please read our release notes for Orchard 1.4.2: http://docs.orchardproject.net/Documentation/Orchard-1-4-Release-NotesVirtu: Virtu 0.9.2: Source Requirements.NET Framework 4 Visual Studio 2010 with SP1 or Visual Studio 2010 Express with SP1 Silverlight 5 Tools for Visual Studio 2010 with SP1 Windows Phone 7 Developer Tools (which includes XNA Game Studio 4) Binaries RequirementsSilverlight 5 .NET Framework 4 XNA Framework 4SharePoint Euro 2012 - UEFA European Football Predictor: havivi.euro2012.wsp (1.0): New fetures:View other users predictions Hide/Show background image (web part property) Installing SharePoint Euro 2012 PredictorSharePoint Euro 2012 Predictor has been developed as a SharePoint Sandbox solution to support SharePoint Online (Office 365) Download the solution havivi.euro2012.wsp from the download page: Downloads Upload this solution to your Site Collection via the solutions area. Click on Activate to make the web parts in the solution available for use in the Site C...State Machine .netmf: State Machine Example: First release.... Contains 3 state machines running on separate threads. Event driven button to change the states. StateMachineEngine to support the Machines Message class with the type of data to send between statesSilverlight socket component: Smark.NetDisk: Smark.NetDisk?????Silverlight ?.net???????????,???????????????????????。Smark.NetDisk??????????,????.net???????????????????????tcp??;???????Silverlight??????????????????????callisto: callisto 2.0.28: Update log: - Extended Scribble protocol. - Updated HTML5 client code - now supports the latest versions of Google Chrome.ExtAspNet: ExtAspNet v3.1.6: ExtAspNet - ?? ExtJS ??? ASP.NET 2.0 ???,????? AJAX ?????????? ExtAspNet ????? ExtJS ??? ASP.NET 2.0 ???,????? AJAX ??????????。 ExtAspNet ??????? JavaScript,?? CSS,?? UpdatePanel,?? ViewState,?? WebServices ???????。 ??????: IE 7.0, Firefox 3.6, Chrome 3.0, Opera 10.5, Safari 3.0+ ????:Apache License 2.0 (Apache) ??:http://bbs.extasp.net/ ??:http://demo.extasp.net/ ??:http://doc.extasp.net/ ??:http://extaspnet.codeplex.com/ ??:http://sanshi.cnblogs.com/ ????: +2012-05-20 v3.1.6 -??RowD...Dynamics XRM Tools: Dynamics XRM Tools BETA 1.0: The Dynamics XRM Tools 1.0 BETA is now available Seperate downloads are available for On Premise and Online as certain features are only available On Premise. This is a BETA build and may not resemble the final release. Many enhancements are in development and will be made available soon. Please provide feedback so that we may learn and discover how to make these tools better.WatchersNET CKEditor™ Provider for DotNetNuke®: CKEditor Provider 1.14.05: Whats New Added New Editor Skin "BootstrapCK-Skin" Added New Editor Skin "Slick" Added Dnn Pages Drop Down to the Link Dialog (to quickly link to a portal tab) changes Fixed Issue #6956 Localization issue with some languages Fixed Issue #6930 Folder Tree view was not working in some cases Changed the user folder from User name to User id User Folder is now used when using Upload Function and User Folder is enabled File-Browser Fixed Resizer Preview Image Optimized the oEmbed Pl...PHPExcel: PHPExcel 1.7.7: See Change Log for details of the new features and bugfixes included in this release. BREAKING CHANGE! From PHPExcel 1.7.8 onwards, the 3rd-party tcPDF library will no longer be bundled with PHPExcel for rendering PDF files through the PDF Writer. The PDF Writer is being rewritten to allow a choice of 3rd party PDF libraries (tcPDF, mPDF, and domPDF initially), none of which will be bundled with PHPExcel, but which can be downloaded seperately from the appropriate sites.GhostBuster: GhostBuster Setup (91520): Added WMI based RestorePoint support Removed test code from program.cs Improved counting. Changed color of ghosted but unfiltered devices. Changed HwEntries into an ObservableCollection. Added Properties Form. Added Properties MenuItem to Context Menu. Added Hide Unfiltered Devices to Context Menu. If you like this tool, leave me a note, rate this project or write a review or Donate to Ghostbuster. Donate to GhostbusterEXCEL??、??、????????:DataPie(??MSSQL 2008、ORACLE、ACCESS 2007): DataPie_V3.2: V3.2, 2012?5?19? ????ORACLE??????。AvalonDock: AvalonDock 2.0.0795: Welcome to the Beta release of AvalonDock 2.0 After 4 months of hard work I'm ready to upload the beta version of AvalonDock 2.0. This new version boosts a lot of new features and now is stable enough to be deployed in production scenarios. For this reason I encourage everyone is using AD 1.3 or earlier to upgrade soon to this new version. The final version is scheduled for the end of June. What is included in Beta: 1) Stability! thanks to all users contribution I’ve corrected a lot of issues...myCollections: Version 2.1.0.0: New in this version : Improved UI New Metro Skin Improved Performance Added Proxy Settings New Music and Books Artist detail Lot of Bug FixingAspxCommerce: AspxCommerce1.1: AspxCommerce - 'Flexible and easy eCommerce platform' offers a complete e-Commerce solution that allows you to build and run your fully functional online store in minutes. You can create your storefront; manage the products through categories and subcategories, accept payments through credit cards and ship the ordered products to the customers. We have everything set up for you, so that you can only focus on building your own online store. Note: To login as a superuser, the username and pass...SiteMap Editor for Microsoft Dynamics CRM 2011: SiteMap Editor (1.1.1616.403): BUG FIX Hide save button when Titles or Descriptions element is selectedMapWindow 6 Desktop GIS: MapWindow 6.1.2: Looking for a .Net GIS Map Application?MapWindow 6 Desktop GIS is an open source desktop GIS for Microsoft Windows that is built upon the DotSpatial Library. This release requires .Net 4 (Client Profile). Are you a software developer?Instead of downloading MapWindow for development purposes, get started with with the DotSpatial template. The extensions you create from the template can be loaded in MapWindow.DotSpatial: DotSpatial 1.2: This is a Minor Release. See the changes in the issue tracker. Minimal -- includes DotSpatial core and essential extensions Extended -- includes debugging symbols and additional extensions Tutorials are available. Just want to run the software? End user (non-programmer) version available branded as MapWindow Want to add your own feature? Develop a plugin, using the template and contribute to the extension feed (you can also write extensions that you distribute in other ways). Components ...New ProjectsBunch of Small Tools: Il s'agit du code source de petits projets principalement en rapport avec le japonais ou le chinois, destinés à des apprenants de ces langues. D'autres petits programmes de ma création peuvent y être ajoutés à ma discrétion. Ces projets ne sont plus en développement, et le code source présenté ici est mis à disposition dans le cadre de mon portefolio.Cat: summaryClínica DECORação: Projeto desenvolvido em ASP.NETDnD Campaing Manager: A little project to create a full campaing manager for D&D 3.5 DMsExcel add-in for Ranges: Slice, dice, and splice Excel ranges to your hearts content. Use RANGE.KEY to do "named argument" style programing.FirstPong: bla bla blaHP TRIM Stream Record Attachment Web App: A simple ASP.Net 4.0 Web application that streams the electronic attachment of a record from Hewlett Packard's TRIM record management software (HP TRIM), to the browser. It uses Routing to retrieve an attachment based on the Record Number, ie: http://localhost/View/D12/45 Where D12/45 is a HP TRIM record number. Code was originally from a HP TRIM sample for ASP.Net 2.0, but I expanded upon it and converted it to .Net 4.0 and added routing for a nicer URL. Json Services: Json Services is a web services framework that intended to make the creation and consumption of SOA based applications easier and more efficient. Json Services framework is built using the .NET framework 4.0 and depends heavily on reflection features of .NET, it is depends on the great Json.NET library for serialization. Json Services framework is intended to be simple and efficient and can be consumed using a wide range of clients, Java Script clients will gain the benefit of automatic...LAVAA: LAVAAlion: abcloja chocolate: Utilização de C# para criar uma loja virtual.Mega Terrain ++: This project presents a method to render large terrains with multiple materials using the Ogre graphics engine.Minería de datos - Reglas de asociación: Laboratorio N° 2 del curso Minería de datos, semestre 1 año 2012. Universidad de Santiago de ChileMNT Cryptography: A very simple cryptography classMsAccess to Sqlite converter: This project aims to create a small application to convert a MSAccess Database file into SQLite format. It needs the SQLite ADO library in order to workMSI Previewer: MSI Previewer is a tool, which extracts the given msi and displays the directory structure in which the files will be placed after the installation. It helps to preview the directory structure of the files present in the msi, which will be placed exactly after installation. muvonni: css3 stylesheet developmentMyModeler: MyModeler is a modeling tool for IT professional and ArchitectsNewSite: First asp.net test project i have on codeplex. I'm not entirely sure where this project is headed at the moment and only have some initial ideas. More details to follow soon.PHLTest: Test team foundationPhoto Studio Nana: ?????????? ???????? ? ???playm_20120517_00365: just a colaboration plan...PROJETO CÓDIGO ABDI: Códigos da ABDIsample project for data entry: hi this is summary for first project....Sharepoint WP List Sinc Mapper: loren ipsum dolorSocialAuth4Net: SocialAuth4Net is open authentication wrapper for populer social platforms for example Facebook, LinkedIn and soon Twitter, Google+tiger: abctweetc: tweetc is a windows command line twitter client written in F#

    Read the article

  • jquery dynamic form plugin: adding nested field support

    - by goliatone
    Hi, Im using the jQuery dynamic form plugin, but i need support for nested field duplication. I would like some advice on how to modify the plugin to add such functionality. Im not a javascript/jQuery developer, so any advice on which route to take will be much appreciated. I can provide the plugin's code: /** * @author Stephane Roucheray * @extends jQuery */ jQuery.fn.dynamicForm = function (plusElmnt, minusElmnt, options){ var source = jQuery(this), minus = jQuery(minusElmnt), plus = jQuery(plusElmnt), template = source.clone(true), fieldId = 0, formFields = "input, checkbox, select, textarea", insertBefore = source.next(), clones = [], defaults = { duration:1000 }; // Extend default options with those provided options = $.extend(defaults, options); isPlusDescendentOfTemplate = source.find("*").filter(function(){ return this == plus.get(0); }); isPlusDescendentOfTemplate = isPlusDescendentOfTemplate.length > 0 ? true : false; function normalizeElmnt(elmnt){ elmnt.find(formFields).each(function(){ var nameAttr = jQuery(this).attr("name"), idAttr = jQuery(this).attr("id"); /* Normalize field name attributes */ if (!nameAttr) { jQuery(this).attr("name", "field" + fieldId + "[]"); } if (!/\[\]$/.exec(nameAttr)) { jQuery(this).attr("name", nameAttr + "[]"); } /* Normalize field id attributes */ if (idAttr) { /* Normalize attached label */ jQuery("label[for='"+idAttr+"']").each(function(){ jQuery(this).attr("for", idAttr + fieldId); }); jQuery(this).attr("id", idAttr + fieldId); } fieldId++; }); }; /* Hide minus element */ minus.hide(); /* If plus element is within the template */ if (isPlusDescendentOfTemplate) { function clickOnPlus(event){ var clone, currentClone = clones[clones.length -1] || source; event.preventDefault(); /* On first add, normalize source */ if (clones.length == 0) { normalizeElmnt(source); currentClone.find(minusElmnt).hide(); currentClone.find(plusElmnt).hide(); }else{ currentClone.find(plusElmnt).hide(); } /* Clone template and normalize it */ clone = template.clone(true).insertAfter(clones[clones.length - 1] || source); normalizeElmnt(clone); /* Normalize template id attribute */ if (clone.attr("id")) { clone.attr("id", clone.attr("id") + clones.length); } plus = clone.find(plusElmnt); minus = clone.find(minusElmnt); minus.get(0).removableClone = clone; minus.click(clickOnMinus); plus.click(clickOnPlus); if (options.limit && (options.limit - 2) > clones.length) { plus.show(); }else{ plus.hide(); } clones.push(clone); } function clickOnMinus(event){ event.preventDefault(); if (this.removableClone.effect && options.removeColor) { that = this; this.removableClone.effect("highlight", { color: options.removeColor }, options.duration, function(){that.removableClone.remove();}); } else { this.removableClone.remove(); } clones.splice(clones.indexOf(this.removableClone),1); if (clones.length == 0){ source.find(plusElmnt).show(); }else{ clones[clones.length -1].find(plusElmnt).show(); } } /* Handle click on plus */ plus.click(clickOnPlus); /* Handle click on minus */ minus.click(function(event){ }); }else{ /* If plus element is out of the template */ /* Handle click on plus */ plus.click(function(event){ var clone; event.preventDefault(); /* On first add, normalize source */ if (clones.length == 0) { normalizeElmnt(source); jQuery(minusElmnt).show(); } /* Clone template and normalize it */ clone = template.clone(true).insertAfter(clones[clones.length - 1] || source); if (clone.effect && options.createColor) { clone.effect("highlight", {color:options.createColor}, options.duration); } normalizeElmnt(clone); /* Normalize template id attribute */ if (clone.attr("id")) { clone.attr("id", clone.attr("id") + clones.length); } if (options.limit && (options.limit - 3) < clones.length) { plus.hide(); } clones.push(clone); }); /* Handle click on minus */ minus.click(function(event){ event.preventDefault(); var clone = clones.pop(); if (clones.length >= 0) { if (clone.effect && options.removeColor) { that = this; clone.effect("highlight", { color: options.removeColor, mode:"hide" }, options.duration, function(){clone.remove();}); } else { clone.remove(); } } if (clones.length == 0) { jQuery(minusElmnt).hide(); } plus.show(); }); } };

    Read the article

  • How do I implement a remove by index method for a singly linked list in Java?

    - by Lars Flyger
    Hi, I'm a student in a programming class, and I need some help with this code I've written. So far I've written an entire linked list class (seen below), yet for some reason the "removeByIndex" method won't work. I can't seem to figure out why, the logic seems sound to me. Is there some problem I don't know about? public class List<T> { //private sub-class Link private class Link { private T value; private Link next; //constructors of Link: public Link (T val) { this.value = val; this.next = null; } public Link (T val, Link next) { this.value = val; this.next = next; } @SuppressWarnings("unused") public T getValue() { return value; } } private static final Exception NoSuchElementException = null; private static final Exception IndexOutOfBoundsException = null; private Link chain = null; //constructors of List: public List() { this.chain = null; } //methods of List: /** * Preconditions: none * Postconditions: returns true if list is empty */ public boolean isEmpty() { return this.chain == null; } /** * Preconditions: none * Postconditions: A new Link is added via add-aux * @param element */ public void add(T element) { this.add_aux(element, this.chain); } /** * Preconditions: none * Postconditions: A new Link is added to the current chain * @param element * @param chain */ private void add_aux(T element, Link chain) { if (chain == null) { //if chain is null set chain to a new Link with a value of //element this.chain = new Link(element); } else if (chain.next != null) { //if chain.next is not null, go to next item in chain and //try //to add element add_aux(element, chain.next); } else { //if chain.next is null, set chain.next equal to a new Link //with value of element. chain.next = new Link(element); } } /** * Preconditions: none * Postconditions: returns the link at the defined index via nthlink_aux * @param index * @return */ private Link nthLink (int index) { return nthLink_aux(index, this.chain); } /** * Preconditions: none * Postconditions: returns the link at the defined index in the specified *chain * @param i * @param c * @return */ private Link nthLink_aux (int i, Link c) { if (i == 0) { return c; } else return nthLink_aux(i-1, c.next); } /** * Preconditions: the specified element is present in the list * Postconditions: the specified element is removed from the list * @param element * @throws Exception */ public void removeElement(T element) throws Exception { if (chain == null) { throw NoSuchElementException; } //while chain's next is not null and the value of chain.next is not //equal to element, //set chain equal to chain.next //use this iteration to go through the linked list. else while ((chain.next != null) && !(chain.next.value.equals(element))){ Link testlink = chain.next; if (testlink.next.value.equals(element)) { //if chain.next is equal to element, bypass the //element. chain.next.next = chain.next.next.next; } else if (testlink.next == null) { throw NoSuchElementException; } } } /** * Preconditions: none * Postsconditions: the Link at the specified index is removed * @param index * @throws Exception */ public void removeByIndex(int index) throws Exception { if (index == 0) { //if index is 0, set chain equal to chain.next chain = chain.next; } else if (index > 0) { Link target = nthLink(index); while (target != null) { if (target.next != null) { target = target.next; } //if target.next is null, set target to null else { target = null; } } return; } else throw IndexOutOfBoundsException; } /** * Preconditions: none * Postconditions: the specified link's value is printed * @param link */ public void printLink (Link link) { if(link != null) { System.out.println(link.value.toString()); } } /** * Preconditions: none * Postconditions: all of the links' values in the list are printed. */ public void print() { //copy chain to a new variable Link head = this.chain; //while head is not null while (!(head == null)) { //print the current link this.printLink(head); //set head equal to the next link head = head.next; } } /** * Preconditions: none * Postconditions: The chain is set to null */ public void clear() { this.chain = null; } /** * Preconditions: none * Postconditions: Places the defined link at the defined index of the list * @param index * @param val */ public void splice(int index, T val) { //create a new link with value equal to val Link spliced = new Link(val); if (index <= 0) { //copy chain Link copy = chain; //set chain equal to spliced chain = spliced; //set chain.next equal to copy chain.next = copy; } else if (index > 0) { //create a target link equal to the link before the index Link target = nthLink(index - 1); //set the target's next equal to a new link with a next //equal to the target's old next target.next = new Link(val, target.next); } } /** * Preconditions: none * Postconditions: Check to see if element is in the list, returns true * if it is and false if it isn't * @param element * @return */ public boolean Search(T element) { if (chain == null) { //return false if chain is null return false; } //while chain's next is not null and the value of chain.next is not //equal to element, //set chain equal to chain.next //use this iteration to go through the linked list. else while ((chain.next != null) && !(chain.next.value.equals(element))) { Link testlink = chain.next; if (testlink.next.value.equals(element)) { //if chain.next is equal to element, return true return true; } else if (testlink.next == null) { return false; } } return false; } /** * Preconditions: none * Postconditions: order of the links in the list is reversed. */ public void reverse() { //copy chain Link current = chain; //set chain equal to null chain = null; while (current != null) { Link save = current; current = current.next; save.next = chain; chain = save; } } }'

    Read the article

  • What's up with OCFS2?

    - by wcoekaer
    On Linux there are many filesystem choices and even from Oracle we provide a number of filesystems, all with their own advantages and use cases. Customers often confuse ACFS with OCFS or OCFS2 which then causes assumptions to be made such as one replacing the other etc... I thought it would be good to write up a summary of how OCFS2 got to where it is, what we're up to still, how it is different from other options and how this really is a cool native Linux cluster filesystem that we worked on for many years and is still widely used. Work on a cluster filesystem at Oracle started many years ago, in the early 2000's when the Oracle Database Cluster development team wrote a cluster filesystem for Windows that was primarily focused on providing an alternative to raw disk devices and help customers with the deployment of Oracle Real Application Cluster (RAC). Oracle RAC is a cluster technology that lets us make a cluster of Oracle Database servers look like one big database. The RDBMS runs on many nodes and they all work on the same data. It's a Shared Disk database design. There are many advantages doing this but I will not go into detail as that is not the purpose of my write up. Suffice it to say that Oracle RAC expects all the database data to be visible in a consistent, coherent way, across all the nodes in the cluster. To do that, there were/are a few options : 1) use raw disk devices that are shared, through SCSI, FC, or iSCSI 2) use a network filesystem (NFS) 3) use a cluster filesystem(CFS) which basically gives you a filesystem that's coherent across all nodes using shared disks. It is sort of (but not quite) combining option 1 and 2 except that you don't do network access to the files, the files are effectively locally visible as if it was a local filesystem. So OCFS (Oracle Cluster FileSystem) on Windows was born. Since Linux was becoming a very important and popular platform, we decided that we would also make this available on Linux and thus the porting of OCFS/Windows started. The first version of OCFS was really primarily focused on replacing the use of Raw devices with a simple filesystem that lets you create files and provide direct IO to these files to get basically native raw disk performance. The filesystem was not designed to be fully POSIX compliant and it did not have any where near good/decent performance for regular file create/delete/access operations. Cache coherency was easy since it was basically always direct IO down to the disk device and this ensured that any time one issues a write() command it would go directly down to the disk, and not return until the write() was completed. Same for read() any sort of read from a datafile would be a read() operation that went all the way to disk and return. We did not cache any data when it came down to Oracle data files. So while OCFS worked well for that, since it did not have much of a normal filesystem feel, it was not something that could be submitted to the kernel mail list for inclusion into Linux as another native linux filesystem (setting aside the Windows porting code ...) it did its job well, it was very easy to configure, node membership was simple, locking was disk based (so very slow but it existed), you could create regular files and do regular filesystem operations to a certain extend but anything that was not database data file related was just not very useful in general. Logfiles ok, standard filesystem use, not so much. Up to this point, all the work was done, at Oracle, by Oracle developers. Once OCFS (1) was out for a while and there was a lot of use in the database RAC world, many customers wanted to do more and were asking for features that you'd expect in a normal native filesystem, a real "general purposes cluster filesystem". So the team sat down and basically started from scratch to implement what's now known as OCFS2 (Oracle Cluster FileSystem release 2). Some basic criteria were : Design it with a real Distributed Lock Manager and use the network for lock negotiation instead of the disk Make it a Linux native filesystem instead of a native shim layer and a portable core Support standard Posix compliancy and be fully cache coherent with all operations Support all the filesystem features Linux offers (ACL, extended Attributes, quotas, sparse files,...) Be modern, support large files, 32/64bit, journaling, data ordered journaling, endian neutral, we can mount on both endian /cross architecture,.. Needless to say, this was a huge development effort that took many years to complete. A few big milestones happened along the way... OCFS2 was development in the open, we did not have a private tree that we worked on without external code review from the Linux Filesystem maintainers, great folks like Christopher Hellwig reviewed the code regularly to make sure we were not doing anything out of line, we submitted the code for review on lkml a number of times to see if we were getting close for it to be included into the mainline kernel. Using this development model is standard practice for anyone that wants to write code that goes into the kernel and having any chance of doing so without a complete rewrite or.. shall I say flamefest when submitted. It saved us a tremendous amount of time by not having to re-fit code for it to be in a Linus acceptable state. Some other filesystems that were trying to get into the kernel that didn't follow an open development model had a lot harder time and a lot harsher criticism. March 2006, when Linus released 2.6.16, OCFS2 officially became part of the mainline kernel, it was accepted a little earlier in the release candidates but in 2.6.16. OCFS2 became officially part of the mainline Linux kernel tree as one of the many filesystems. It was the first cluster filesystem to make it into the kernel tree. Our hope was that it would then end up getting picked up by the distribution vendors to make it easy for everyone to have access to a CFS. Today the source code for OCFS2 is approximately 85000 lines of code. We made OCFS2 production with full support for customers that ran Oracle database on Linux, no extra or separate support contract needed. OCFS2 1.0.0 started being built for RHEL4 for x86, x86-64, ppc, s390x and ia64. For RHEL5 starting with OCFS2 1.2. SuSE was very interested in high availability and clustering and decided to build and include OCFS2 with SLES9 for their customers and was, next to Oracle, the main contributor to the filesystem for both new features and bug fixes. Source code was always available even prior to inclusion into mainline and as of 2.6.16, source code was just part of a Linux kernel download from kernel.org, which it still is, today. So the latest OCFS2 code is always the upstream mainline Linux kernel. OCFS2 is the cluster filesystem used in Oracle VM 2 and Oracle VM 3 as the virtual disk repository filesystem. Since the filesystem is in the Linux kernel it's released under the GPL v2 The release model has always been that new feature development happened in the mainline kernel and we then built consistent, well tested, snapshots that had versions, 1.2, 1.4, 1.6, 1.8. But these releases were effectively just snapshots in time that were tested for stability and release quality. OCFS2 is very easy to use, there's a simple text file that contains the node information (hostname, node number, cluster name) and a file that contains the cluster heartbeat timeouts. It is very small, and very efficient. As Sunil Mushran wrote in the manual : OCFS2 is an efficient, easily configured, quickly installed, fully integrated and compatible, feature-rich, architecture and endian neutral, cache coherent, ordered data journaling, POSIX-compliant, shared disk cluster file system. Here is a list of some of the important features that are included : Variable Block and Cluster sizes Supports block sizes ranging from 512 bytes to 4 KB and cluster sizes ranging from 4 KB to 1 MB (increments in power of 2). Extent-based Allocations Tracks the allocated space in ranges of clusters making it especially efficient for storing very large files. Optimized Allocations Supports sparse files, inline-data, unwritten extents, hole punching and allocation reservation for higher performance and efficient storage. File Cloning/snapshots REFLINK is a feature which introduces copy-on-write clones of files in a cluster coherent way. Indexed Directories Allows efficient access to millions of objects in a directory. Metadata Checksums Detects silent corruption in inodes and directories. Extended Attributes Supports attaching an unlimited number of name:value pairs to the file system objects like regular files, directories, symbolic links, etc. Advanced Security Supports POSIX ACLs and SELinux in addition to the traditional file access permission model. Quotas Supports user and group quotas. Journaling Supports both ordered and writeback data journaling modes to provide file system consistency in the event of power failure or system crash. Endian and Architecture neutral Supports a cluster of nodes with mixed architectures. Allows concurrent mounts on nodes running 32-bit and 64-bit, little-endian (x86, x86_64, ia64) and big-endian (ppc64) architectures. In-built Cluster-stack with DLM Includes an easy to configure, in-kernel cluster-stack with a distributed lock manager. Buffered, Direct, Asynchronous, Splice and Memory Mapped I/Os Supports all modes of I/Os for maximum flexibility and performance. Comprehensive Tools Support Provides a familiar EXT3-style tool-set that uses similar parameters for ease-of-use. The filesystem was distributed for Linux distributions in separate RPM form and this had to be built for every single kernel errata release or every updated kernel provided by the vendor. We provided builds from Oracle for Oracle Linux and all kernels released by Oracle and for Red Hat Enterprise Linux. SuSE provided the modules directly for every kernel they shipped. With the introduction of the Unbreakable Enterprise Kernel for Oracle Linux and our interest in reducing the overhead of building filesystem modules for every minor release, we decide to make OCFS2 available as part of UEK. There was no more need for separate kernel modules, everything was built-in and a kernel upgrade automatically updated the filesystem, as it should. UEK allowed us to not having to backport new upstream filesystem code into an older kernel version, backporting features into older versions introduces risk and requires extra testing because the code is basically partially rewritten. The UEK model works really well for continuing to provide OCFS2 without that extra overhead. Because the RHEL kernel did not contain OCFS2 as a kernel module (it is in the source tree but it is not built by the vendor in kernel module form) we stopped adding the extra packages to Oracle Linux and its RHEL compatible kernel and for RHEL. Oracle Linux customers/users obviously get OCFS2 included as part of the Unbreakable Enterprise Kernel, SuSE customers get it by SuSE distributed with SLES and Red Hat can decide to distribute OCFS2 to their customers if they chose to as it's just a matter of compiling the module and making it available. OCFS2 today, in the mainline kernel is pretty much feature complete in terms of integration with every filesystem feature Linux offers and it is still actively maintained with Joel Becker being the primary maintainer. Since we use OCFS2 as part of Oracle VM, we continue to look at interesting new functionality to add, REFLINK was a good example, and as such we continue to enhance the filesystem where it makes sense. Bugfixes and any sort of code that goes into the mainline Linux kernel that affects filesystems, automatically also modifies OCFS2 so it's in kernel, actively maintained but not a lot of new development happening at this time. We continue to fully support OCFS2 as part of Oracle Linux and the Unbreakable Enterprise Kernel and other vendors make their own decisions on support as it's really a Linux cluster filesystem now more than something that we provide to customers. It really just is part of Linux like EXT3 or BTRFS etc, the OS distribution vendors decide. Do not confuse OCFS2 with ACFS (ASM cluster Filesystem) also known as Oracle Cloud Filesystem. ACFS is a filesystem that's provided by Oracle on various OS platforms and really integrates into Oracle ASM (Automatic Storage Management). It's a very powerful Cluster Filesystem but it's not distributed as part of the Operating System, it's distributed with the Oracle Database product and installs with and lives inside Oracle ASM. ACFS obviously is fully supported on Linux (Oracle Linux, Red Hat Enterprise Linux) but OCFS2 independently as a native Linux filesystem is also, and continues to also be supported. ACFS is very much tied into the Oracle RDBMS, OCFS2 is just a standard native Linux filesystem with no ties into Oracle products. Customers running the Oracle database and ASM really should consider using ACFS as it also provides storage/clustered volume management. Customers wanting to use a simple, easy to use generic Linux cluster filesystem should consider using OCFS2. To learn more about OCFS2 in detail, you can find good documentation on http://oss.oracle.com/projects/ocfs2 in the Documentation area, or get the latest mainline kernel from http://kernel.org and read the source. One final, unrelated note - since I am not always able to publicly answer or respond to comments, I do not want to selectively publish comments from readers. Sometimes I forget to publish comments, sometime I publish them and sometimes I would publish them but if for some reason I cannot publicly comment on them, it becomes a very one-sided stream. So for now I am going to not publish comments from anyone, to be fair to all sides. You are always welcome to email me and I will do my best to respond to technical questions, questions about strategy or direction are sometimes not possible to answer for obvious reasons.

    Read the article

  • JSON object array to store data of a form in local storage temporary (PhoneGap project)

    - by Nadeesha
    I am building a data aqusition system using PhoneGap. .I am trying to store my form data temporary on local storage using JSON,Data should be visible after I close and reopen the application (after pressing Get Data button),But after I close it only the lastly entered record is visible This is my code <!DOCTYPE html> <html> <head> <title>Household Profile DB storage</title> <meta charset="utf-8"> <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1,width=device-width" /> <link rel="stylesheet" href="jquery.mobile-1.4.2/jquery.mobile-1.4.2.min.css"> <link rel="stylesheet" href="css/table.css"> <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script> <script type="text/javascript" src="jquery.mobile-1.4.2/jquery.mobile-1.4.2.min.js"></script> <script type="text/javascript" src="js/iscroll.js"></script> <script type="text/javascript" charset="utf-8"> function onDeviceReady() { persistData(homeId,owner,gramaND,contactNo,address,race); } function saveLocal(form){ if (window.localStorage) { var fhomeId = form.homeId.value, fowner = form.owner.value, fgramaND = form.gramaND.value, fcontactNo= form.contactNo.value, faddress = form.address.value, frace = form.race.value; alert("hi"); var highscores = [{"homeId": fhomeId, "owner":fowner, "gramaND":fgramaND, "contactNo":fcontactNo, "address":faddress, "race":frace}]; localStorage.setItem("highscores",JSON.stringify(highscores)); alert("The data has been stored successfully."); } else { alert("Your Browser does not support LocalStorage."); } } function readLocal(){ if (window.localStorage) { var scores =[]; //Get the highscores object scores = localStorage.getItem("highscores"); scores = JSON.parse(scores); for (i=0;i<scores.length;i++){ var text = "homeId :"+scores[i].homeId +"<br>"+ "owner:"+ scores[i].owner+"<br>"+ "address"+scores[i].address +"<br>"+ "gramaND"+scores[i].gramaND +"<br>"+ "contactNo"+scores[i].contactNo+"<br>" + '<Button value="DELETE" onclick="'+scores.splice(i, 0)+'><>/Button>'; var tbodyx = document.getElementsByTagName("tbody"); var tr=document.createElement("TR"); var td=document.createElement("TD"); td.innerHTML = text; tr.appendChild(td); tbody.appendChild(tr); } } } </script> </head> <body> <div data-role="page" id="page1"> <!--/header--> <div data-role="header" data-position="inline" data-theme="b"> <a href="#" data-icon="back" data-rel="back" title="Go back">Back</a> <h1>Household Profile</h1> <a href="index.html" data-icon="home">Menu</a> </div> <!--/header--> <div id="wrapper"> <form id="userInput" action ="" method="GET"> <div data-role="content"> <div data-role="fieldcontain"> <label > Home ID </label> <input class="inputClass" id="homeId" placeholder="H0001" value="" data-mini="true" type="text"> </div> <div data-role="fieldcontain"> <label > Owner </label> <input class="inputClass" id="owner" placeholder="Aberathne" value="" type="text"> </div> <div data-role="fieldcontain"> <label class="select">GramaNiladhari Division</label> <select class="inputClass" id="gramaND"> <option value="GramaNiladhari Division 1">GramaNiladhari Division 1</option> <option value="GramaNiladhari Division 2">GramaNiladhari Division 2</option> <option value="GramaNiladhari Division 3">GramaNiladhari Division 3</option> <option value="GramaNiladhari Division 4">GramaNiladhari Division 4</option> </select> </div> <div data-role="fieldcontain"> <label > Contact No </label> <input class="inputClass" id="contactNo" placeholder="071-9545-073" value="" type="number"> </div> <div data-role="fieldcontain"> <label >Address:</label> <textarea cols="40" rows="8" class="inputClass" id="address"></textarea> </div> <div class="ui-block-a"><button type="submit" data-theme="d">Location in a Map</button></div> <div data-role="fieldcontain"> <label >Race</label> <select class="inputClass" id="race"> <option value=" Sinhalese"> Sinhalese</option> <option value=" Sri Lanka Tamils"> Sri Lanka Tamils</option> <option value=" Moors"> Moors</option> <option value=" Indian Tamils "> Indian Tamils </option> <option value=" Malays "> Malays </option> <option value=" Burghers "> Burghers </option> </select> </div> <input class="buttonClass" type="button" value="Insert Data" onclick="saveLocal(this.form);"> </div> </form> </div> <input class="buttonClass" type="button" value="get Data" onclick="readLocal();"> <!-- <p id="dhomeId"></p> <p id="downer"></p> <p id="dgramaND"></p> <p id="dcontactNo"></p> <p id="daddress"></p> <p id="drace"></p>--> <table border="1"> <tbody id="tbody"> <tr><td>test1</td></tr> <tr><td>test2</td></tr> </tbody> </table> </div> </body> </html> Also I need to expand my code to edit and delete record from local storage.

    Read the article

  • Merging multiple Google calendar feeds into one JSON object in javascript

    - by Jeramy
    I am trying to bring in the JSON feeds from multiple Google calendars so that I can sort the upcoming events and display the next X number in an "Upcoming Events" list. I have this working with Yahoo! pipes but I want to get away from using a 3rd party to aggregate. I think I am close, but I cannot get the JSON objects created correctly. I am getting the data into the array but not in JSON format, so I can't manipulate it. I have tried var myJsonString = JSON.stringify(JSONData); using https://github.com/douglascrockford/JSON-js but that just threw errors. I suspect because my variable is in the wrong starting format. I have tried just calling the feed like: $.getJSON(url); and creating a function concant1() to do the JSONData=JSONData.concat(data);, but it doesn't fire and I think it would produce the same end result anyway. I have also tried several other methods of getting the end result I want with varying degrees of doom. Here is the closest I have come so far: var JSONData = new Array(); var urllist = ["https://www.google.com/calendar/feeds/dg61asqgqg4pust2l20obgdl64%40group.calendar.google.com/public/full?orderby=starttime&max-results=3&sortorder=ascending&futureevents=true&ctz=America/New_York&singleevents=true&alt=json&callback=concant1","https://www.google.com/calendar/feeds/5oc3kvp7lnu5rd4krg2skcu2ng%40group.calendar.google.com/public/full?orderby=starttime&max-results=3&sortorder=ascending&futureevents=true&ctz=America/New_York&singleevents=true&alt=json&callback=concant1","http://www.google.com/calendar/feeds/rine4umu96kl6t46v4fartnho8%40group.calendar.google.com/public/full?orderby=starttime&max-results=3&sortorder=ascending&futureevents=true&ctz=America/New_York&singleevents=true&alt=json&callback=concant1"]; urllist.forEach(function addFeed(url){ alert("The URL being used: "+ url); if (void 0 != JSONData){JSONData=JSONData.concat($.getJSON(url));} else{JSONData = $.getJSON(url);} alert("The count from concantonated JSONData: "+JSONData.length); }); document.write("The final count from JSONData: "+JSONData.length+"<p>"); console.log(JSONData) UPDATE: Now with full working source!! :) If anyone would like to make suggestions on how to improve the code's efficiency it would be gratefully accepted. I hope others find this useful.: // GCal MFA - Google Calendar Multiple Feed Aggregator // Useage: GCalMFA(CIDs,n); // Where 'CIDs' is a list of comma seperated Google calendar IDs in the format: [email protected], and 'n' is the number of results to display. // While the contained console.log(); outputs are really handy for testing, you will probably waant to remove them for regular usage // Author: Jeramy Kruser - http://jeramy.kruser.me //onerror=function (d, f, g){alert (d+ "\n"+ f+ "\n");} if (!window.console) {console = {log: function() {}};} document.body.className += ' js-enabled'; // Global variables var urllist = []; var maxResults = 3; // The default is 3 results unless a value is sent var JSONData = {}; var eventCount = 0; var errorLog = ""; JSONData = { count: 0, value : { description: "Aggregates multiple Google calendar feeds into a single sorted list", generator: "StackOverflow communal coding - Thanks for the assist Patrick M", website: "http://jeramy.kruser.me", author: "Jeramy & Kasey Kruser", items: [] }}; // For putting dates from feed into a format that can be read by the Date function for calculating event length. function parse (str) { // validate year as 4 digits, month as 01-12, and day as 01-31 str = str.match (/^(\d{4})(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])$/); if (str) { // make a date str[0] = new Date ( + str[1], + str[2] - 1, + str[3]); // check if month stayed the same (ie that day number is valid) if (str[0].getMonth () === + str[2] - 1) { return str[0]; } } return undefined; } //For outputting to HTML function output() { var months, day_in_ms, summary, i, item, eventlink, title, calendar, where,dtstart, dtend, endyear, endmonth, endday, startyear, startmonth, startday, endmonthdayyear, eventlinktitle, startmonthday, length, curtextval, k; // Array of month names from numbers for page display. months = {'0':'January', '1':'February', '2':'March', '3':'April', '4':'May', '5':'June', '6':'July', '7':'August', '8':'September', '9':'October', '10':'November', '11':'December'}; // For use in calculating event length. day_in_ms = 24 * 60 * 60 * 1000; // Instantiate HTML Arrays. summary = []; for (i = 0; i < maxResults; i+=1 ) { //console.log("i: "+i+" < "+"maxResults: "+ maxResults); if (!(JSONData.value.items[i] === undefined)) { item = JSONData.value.items[i]; // Grabbing data for each event in the feed. eventlink = item.link[0]; title = item.title.$t; // Only display the calendar title if there is more than one calendar = ""; if (urllist.length > 1) { calendar = '<br />Calendar: <a href="https://www.google.com/calendar/embed?src=' + item.gd$who[0].email + '&ctz=America/New_York">' + item.author[0].name.$t + '<\/a> (<a href="https://www.google.com/calendar/ical/' + item.gd$who[0].email + '/public/basic.ics">iCal<\/a>)'; } // Grabbing event location, if entered. if ( item.gd$where[0].valueString !== "" ) { where = '<br />' + (item.gd$where[0].valueString); } else { where = (""); } // Grabbing start date and putting in form YYYYmmdd. Subtracting one day from dtend to fix Google's habit of ending an all-day event at midnight on the following day. dtstart = new Date(parse(((item.gd$when[0].startTime).substring(0,10)).replace(/-/g,""))); dtend = new Date(parse(((item.gd$when[0].endTime).substring(0,10)).replace(/-/g,"")) - day_in_ms); // Put dates in pretty form for display. endyear = dtend.getFullYear(); endmonth = months[dtend.getMonth()]; endday = dtend.getDate(); startyear = dtstart.getFullYear(); startmonth = months[dtstart.getMonth()]; startday = dtstart.getDate(); //consolidate some much-used variables for HTML output. endmonthdayyear = endmonth + ' ' + endday + ', ' + endyear; eventlinktitle = '<a href="' + eventlink + '">' + title + '<\/a>'; startmonthday = startmonth + ' ' + startday; // Calculates the number of days between each event's start and end dates. length = ((dtend - dtstart) / day_in_ms); // HTML for each event, depending on which div is available on the page (different HTML applies). Only one div can exist on any one page. if (document.getElementById("homeCalendar") !== null ) { // If the length of the event is greater than 0 days, show start and end dates. if ( length > 0 && startmonth !== endmonth && startday === endday ) { summary[i] = ('<h3>' + eventlink + '">' + startmonthday + ', ' + startyear + ' - ' + endmonthdayyear + '<\/a><\/h3><p>' + title + '<\/p>'); } // If the length of the event is greater than 0 and begins and ends within the same month, shorten the date display. else if ( length > 0 && startmonth === endmonth && startyear === endyear ) { summary[i] = ('<h3><a href="' + eventlink + '">' + startmonthday + '-' + endday + ', ' + endyear + '<\/a><\/h3><p>' + title + '<\/p>'); } // If the length of the event is greater than 0 and begins and ends within different months of the same year, shorten the date display. else if ( length > 0 && startmonth !== endmonth && startyear === endyear ) { summary[i] = ('<h3><a href="' + eventlink + '">' + startmonthday + ' - ' + endmonthdayyear + '<\/a><\/h3><p>' + title + '<\/p>'); } // If the length of the event is less than one day (length < = 0), show only the start date. else { summary[i] = ('<h3><a href="' + eventlink + '">' + startmonthday + ', ' + startyear + '<\/a><\/h3><p>' + title + '<\/p>'); } } else if (document.getElementById("allCalendar") !== null ) { // If the length of the event is greater than 0 days, show start and end dates. if ( length > 0 && startmonth !== endmonth && startday === endday ) { summary[i] = ('<li>' + eventlinktitle + '<br />' + startmonthday + ', ' + startyear + ' - ' + endmonthdayyear + where + calendar + '<br />&#160;<\/li>'); } // If the length of the event is greater than 0 and begins and ends within the same month, shorten the date display. else if ( length > 0 && startmonth === endmonth && startyear === endyear ) { summary[i] = ('<li>' + eventlinktitle + '<br />' + startmonthday + '-' + endday + ', ' + endyear + where + calendar + '<br />&#160;<\/li>'); } // If the length of the event is greater than 0 and begins and ends within different months of the same year, shorten the date display. else if ( length > 0 && startmonth !== endmonth && startyear === endyear ) { summary[i] = ('<li>' + eventlinktitle + '<br />' + startmonthday + ' - ' + endmonthdayyear + where + calendar + '<br />&#160;<\/li>'); } // If the length of the event is less than one day (length < = 0), show only the start date. else { summary[i] = ('<li>' + eventlinktitle + '<br />' + startmonthday + ', ' + startyear + where + calendar + '<br />&#160;<\/li>'); } } } if (summary[i] === undefined) { summary[i] = "";} //console.log(summary[i]); } console.log(JSONData); // Puts the HTML into the div with the appropriate id. Each page can have only one. if (document.getElementById("homeCalendar") !== null ) { curtextval = document.getElementById("homeCalendar"); console.log("homeCalendar: "+curtextval); } else if (document.getElementById("oneCalendar") !== null ) { curtextval = document.getElementById("oneCalendar"); console.log("oneCalendar: "+curtextval); } else if (document.getElementById("allCalendar") !== null ) { curtextval = document.getElementById("allCalendar"); console.log("allCalendar: "+curtextval); } if (curtextval.innerHTML.length < 100) { errorLog += '<div id="noEvents">No events found.</div>'; } for (k = 0; k<maxResults; k+=1 ) { curtextval.innerHTML = curtextval.innerHTML + summary[k]; } if (eventCount === 0) { errorLog += '<div id="noEvents">No events found.</div>'; } if (document.getElementById("homeCalendar") === null ) { curtextval.innerHTML = '<ul>' + curtextval.innerHTML + '<\/ul>'; } if (errorLog !== "") { curtextval.innerHTML += errorLog; } } // For taking in each feed, breaking out the events and sorting them into the object by date function sortFeed(event) { var tempEntry, i; tempEntry = event; i = 0; console.log("*** New incoming event object #"+eventCount+" ***"); console.log(event.title.$t); console.log(event); //console.log("i = " + i + " and maxResults " + maxResults); while(i<maxResults) { console.log("i = " + i + " < maxResults " + maxResults); console.log("Sorting event = " + event.title.$t + " by date of " + event.gd$when[0].startTime.substring(0,10).replace(/-/g,"")); if (JSONData.value.items[i]) { console.log("JSONData.value.items[" + i + "] exists and has a startTime of " + JSONData.value.items[i].gd$when[0].startTime.substring(0,10).replace(/-/g,"")); if (event.gd$when[0].startTime.substring(0,10).replace(/-/g,"")<JSONData.value.items[i].gd$when[0].startTime.substring(0,10).replace(/-/g,"")) { console.log("The incoming event value of " + event.gd$when[0].startTime.substring(0,10).replace(/-/g,"") + " is < " + JSONData.value.items[i].gd$when[0].startTime.substring(0,10).replace(/-/g,"")); tempEntry = JSONData.value.items[i]; console.log("Existing JSONData.value.items[" + i + "] value " + JSONData.value.items[i].gd$when[0].startTime.substring(0,10).replace(/-/g,"") + " stored in tempEntry"); JSONData.value.items[i] = event; console.log("Position JSONData.value.items[" + i + "] set to new value: " + event.gd$when[0].startTime.substring(0,10).replace(/-/g,"")); event = tempEntry; console.log("Now sorting event = " + event.title.$t + " by date of " + event.gd$when[0].startTime.substring(0,10).replace(/-/g,"")); } else { console.log("The incoming event value of " + event.gd$when[0].startTime.substring(0,10).replace(/-/g,"") + " is > " + JSONData.value.items[i].gd$when[0].startTime.substring(0,10).replace(/-/g,"") + " moving on..."); } } else { JSONData.value.items[i] = event; console.log("JSONData.value.items[" + i + "] does not exist so it was set to the Incoming value of " + event.gd$when[0].startTime.substring(0,10).replace(/-/g,"")); i = maxResults; } i += 1; } } // For completing the aggregation function complete(result) { var str, j, item; // Track the number of calls completed back, we're not done until all URLs have processed if( complete.count === undefined ){ complete.count = urllist.length; } console.log("complete.count = "+complete.count); console.log(result.feed); if(result.feed.entry){ JSONData.count = maxResults; // Check each incoming item against JSONData.value.items console.log("*** Begin Sorting " + result.feed.entry.length + " Events ***"); //console.log(result.feed.entry); result.feed.entry.forEach( function(event){ eventCount += 1; sortFeed(event); } ); } if( (complete.count-=1)<1 ) { console.log("*** Done Sorting ***"); output(); } } // This is the main function. It takes in the list of Calendar IDs and the number of results to display function GCalMFA(list,results){ var i, calPreProperties, calPostProperties1, calPostProperties2; calPreProperties = "https://www.google.com/calendar/feeds/"; calPostProperties1 = "/public/full?max-results="; calPostProperties2 = "&orderby=starttime&sortorder=ascending&futureevents=true&ctz=America/New_York&singleevents=true&alt=json&callback=?"; if (list) { if (results) { maxResults = results; } urllist = list.split(','); for (i = 0; i < urllist.length; i+=1 ){ if (urllist[i] === 0){ urllist.splice(i,1);} else{ urllist[i] = calPreProperties + urllist[i] + calPostProperties1+maxResults+calPostProperties2;} } console.log("There are " + urllist.length + " URLs"); urllist.forEach(function addFeed(url){ $.getJSON(url, complete); }); } else { errorLog += '<div id="noURLs">No calendars have been selected.</div>'; output(); } }

    Read the article

  • AngularJS databinding

    - by user3652865
    How can I add multiple values to one object in an Array. I am having Environment and Cluster, I am able to assign multiple clusters to one environment. Now I want to add application name to this environment and cluster pair. I am having page called "Add Application". Here I am using select menu to for environment and Cluster. My first question is, when I select environment then want to show only those clusters which are assigned to that environment name. And assign application name to that pair. Also should be able to edit the Application field. I am using environmentServices and clusterServices to store updated data. link of JSFiddle: http://jsfiddle.net/avinashMaddy/J2KLK/5/ Please if someone can help me in this. Below is my code: <div class="maincontent" ng-controller="manageApplicationController"> <div class="article"> <form> <section> <!-- Environment --> <div class="col-md-4"> <label>Environment:</label> <select ng-model="newApp.selectedEnvironment" class="form-control" ng-options="environment.name for environment in environments"> <option value='' disabled style='display:none;'> Select Environment </option> </select> <span> <select ng-switch-when="true" disabled ng-model="newApp.selectedEnvironment" class="form-control" ng-options="environment.name for environment in environments"> <option value='' disabled style='display:none;'> Select Environment </option> </select> </span> </div> <!-- Cluster --> <div class="col-md-4"> <label>Cluster:</label> <span ng-switch on="newApp.showCancel"> <select ng-switch-default ng-model="newApp.selectedCluster" class="form-control" ng-options="cluster for cluster in clusters"> <option value='' disabled style='display:none;'> Select Environment </option> </select> <select ng-switch-when="true" disabled ng-model="newApp.selectedCluster" class="form-control" ng-options="cluster for cluster in clusters"> <option value='' disabled style='display:none;'> Select Environment </option> </select> </span> </div> <!-- Application Name --> <div class="col-md-4"> <label>Application Name:</label> <input type="text" class="form-control" name="applicationName" placeholder="Application" ng-model="app.name" required> <br/> <input type="hidden" ng-model="app.id" /> </div> </section> <!-- submit button --> <section class="col-md-12"> <button type="button" class="btn btn-default pull-right" ng-click="saveNewApplicatons()">Save</button> </section> </form> </div> <!-- table --> <div class="article"> <table class="table table-bordered table-striped"> <tr> <th colspan="6"> <div class="pull-left">Cluster Info</div> </th> </tr> <tr> <th>Environment</th> <th>Cluster</th> <th>Application</th> <th>Edit</th> <th>Header Ifo</th> </tr> <tr ng-repeat="app in applications"> <td>{{app.environment}}</td> <td>{{app.cluster}}</td> <td>{{app.name}}</td> <td> <a href="" ng-click="edit(app.id)" title="Edit">edit</span></a> | <a href="" ng-click="remove(app.id)" title="Delete">delete</a> </td> <td> <!-- Add template --> <script type="text/ng-template" id="addHederInfo.html"> <div class="modal-header"> <h3>Add Header Info</h3> </div> <div class="modal-body"> <input type="text" class="form-control" name="eName" placeholder="Header Key" ng-model="$parent.header.key"> <br/> <input type="text" class="form-control" name="eName" placeholder="Header Value" ng-model="$parent.header.value"> <br /> <input type="hidden" ng-model="header.id" /> <section> <div class="pull-right"> <button class="btn btn-primary" ng-click="saveHeader()">Add</button> <button class="btn btn-warning" ng-click="cancel()">Close</button> </div> </section> </div> <div class="modal-footer"> <h3>Existing Header Info for </h3> <table class="table table-bordered table-striped"> <tr> <th>Header Key</th> <th>Header Vlaue</th> </tr> <tr ng-repeat="header in headers"> <td>{{header.key}}</td> <td>{{header.value}}</td> </tr> </table> </div> </script> <!-- /Add template --> <script type="text/ng-template" id="editHederInfo.html"> <div class="modal-header"> <h3>Edit Header Info</h3> </div> <div class="modal-body"> <input type="text" class="form-control" name="eName" placeholder="Header Key" ng-model="$parent.header.key"> <br/> <input type="text" class="form-control" name="eName" placeholder="Header Value" ng-model="$parent.header.value"> <br /> <input type="hidden" ng-model="header.id" /> <section> <div class="pull-right"> <button class="btn btn-primary" ng-click="saveHeader()">Update</button> <button class="btn btn-warning" ng-click="cancel()">Close</button> </div> </section> </div> <div class="modal-footer"> <h3>Existing Header Info for</h3> <table class="table table-bordered table-striped"> <tr> <th>Header Key</th> <th>Header Vlaue</th> <th>Edit</th> </tr> <tr ng-repeat="header in headers"> <td>{{header.key}}</td> <td>{{header.value}}</td> <td> <a href="" ng-click="editHeader(header.id)" title="Edit"><span class="glyphicon glyphicon-edit" ></span></a> | <a href="" ng-click="removeHeader(header.id)" title="Edit"><span class="glyphicon glyphicon-trash"></span></a> </td> </tr> </table> </div> </script> <!-- Add template --> <!-- /Add template --> <a href="" ng-click="addInfo()">Add</a> | <a href="" ng-click="editInfo()">Edit</a> </td> </tr> </table> </div> </div> Controller.js: var apsApp = angular.module('apsApp', []); apsApp.service('clusterService', function(){ var clusters=[]; //simply returns the environment list this.list = function () { return clusters; }; }); apsApp.service('environmentService', function(){ var environments=[ {name :'DEV',}, {name:'PROD',}, {name:'QA',}, {name:'Linux_Dev',} ]; //simply returns the environment list this.list = function () { return environments; }; apsApp.controller('manageApplicationController', function ($scope, environmentService, clusterService) { var uid = 0; $scope.environments= environmentService.list(); $scope.clusters= clusterService.list(); $scope.newApp = {}; $scope.newApp.selectedEnvironment = $scope.environments[0]; $scope.newApp.selectedCluster = $scope.clusters[0]; $scope.newApp.buttonLabel = 'Save'; $scope.newApp.showCancel = false; /*$scope.applications=[ {'name': 'Enterprice App Store' }, {'name': 'UsageGateway'}, {'name': 'Click 2 Fill'}, {'name': 'ATT SmartWiFi'} ];*/ //add new application $scope.saveNewApplicatons = function() { if ($scope.select.id == undefined) { //if this is new application, add it in applications array $scope.clusters.push({ id: uid++, cluster: $scope.newApp.cluster, environment: $scope.newApp.selectedEnvironment }); } else { $scope.clusters[$scope.select.id].cluster = $scope.select.cluster; $scope.newApp.id = undefined; $scope.newApp.buttonLabel = 'Save Cluster'; $scope.newApp.showCancel = false; }; //clear the add appplicaitons form $scope.newApp.selectedEnvironment = $scope.environments[0]; }; //delete application $scope.remove = function (id) { //search app with given id and delete it for (i in $scope.clusters) { if ($scope.clusters[i].id == id) { confirm("This Cluster will get deleted permanently"); $scope.clusters.splice(i, 1); $scope.clust = {}; } } }; $scope.cancelUpdate = function () { $scope.newApp.buttonLabel = 'Save Cluster'; $scope.newApp.showCancel = false; $scope.newApp.id = undefined; $scope.newApp.cluster = ""; $scope.newApp.selectedEnvironment = $scope.environments[0]; }; });

    Read the article

  • Help with Nicedit - removeFormat function

    - by Franck
    Hello, I'm trying to get around Nicedit, and especially the "removeFormat" function. The problem is I cannot find the "removeFormat" method source code in the code below. The JS syntax looks strange to me. Can someone help me ? /* NicEdit - Micro Inline WYSIWYG * Copyright 2007-2008 Brian Kirchoff * * NicEdit is distributed under the terms of the MIT license * For more information visit http://nicedit.com/ * Do not remove this copyright message */ var bkExtend = function(){ var A = arguments; if (A.length == 1) { A = [this, A[0]] } for (var B in A[1]) { A[0][B] = A[1][B] } return A[0] }; function bkClass(){ } bkClass.prototype.construct = function(){ }; bkClass.extend = function(C){ var A = function(){ if (arguments[0] !== bkClass) { return this.construct.apply(this, arguments) } }; var B = new this(bkClass); bkExtend(B, C); A.prototype = B; A.extend = this.extend; return A }; var bkElement = bkClass.extend({ construct: function(B, A){ if (typeof(B) == "string") { B = (A || document).createElement(B) } B = $BK(B); return B }, appendTo: function(A){ A.appendChild(this); return this }, appendBefore: function(A){ A.parentNode.insertBefore(this, A); return this }, addEvent: function(B, A){ bkLib.addEvent(this, B, A); return this }, setContent: function(A){ this.innerHTML = A; return this }, pos: function(){ var C = curtop = 0; var B = obj = this; if (obj.offsetParent) { do { C += obj.offsetLeft; curtop += obj.offsetTop } while (obj = obj.offsetParent) } var A = (!window.opera) ? parseInt(this.getStyle("border-width") || this.style.border) || 0 : 0; return [C + A, curtop + A + this.offsetHeight] }, noSelect: function(){ bkLib.noSelect(this); return this }, parentTag: function(A){ var B = this; do { if (B && B.nodeName && B.nodeName.toUpperCase() == A) { return B } B = B.parentNode } while (B); return false }, hasClass: function(A){ return this.className.match(new RegExp("(\s|^)nicEdit-" + A + "(\s|$)")) }, addClass: function(A){ if (!this.hasClass(A)) { this.className += " nicEdit-" + A } return this }, removeClass: function(A){ if (this.hasClass(A)) { this.className = this.className.replace(new RegExp("(\s|^)nicEdit-" + A + "(\s|$)"), " ") } return this }, setStyle: function(A){ var B = this.style; for (var C in A) { switch (C) { case "float": B.cssFloat = B.styleFloat = A[C]; break; case "opacity": B.opacity = A[C]; B.filter = "alpha(opacity=" + Math.round(A[C] * 100) + ")"; break; case "className": this.className = A[C]; break; default: B[C] = A[C] } } return this }, getStyle: function(A, C){ var B = (!C) ? document.defaultView : C; if (this.nodeType == 1) { return (B && B.getComputedStyle) ? B.getComputedStyle(this, null).getPropertyValue(A) : this.currentStyle[bkLib.camelize(A)] } }, remove: function(){ this.parentNode.removeChild(this); return this }, setAttributes: function(A){ for (var B in A) { this[B] = A[B] } return this } }); var bkLib = { isMSIE: (navigator.appVersion.indexOf("MSIE") != -1), addEvent: function(C, B, A){ (C.addEventListener) ? C.addEventListener(B, A, false) : C.attachEvent("on" + B, A) }, toArray: function(C){ var B = C.length, A = new Array(B); while (B--) { A[B] = C[B] } return A }, noSelect: function(B){ if (B.setAttribute && B.nodeName.toLowerCase() != "input" && B.nodeName.toLowerCase() != "textarea") { B.setAttribute("unselectable", "on") } for (var A = 0; A < B.childNodes.length; A++) { bkLib.noSelect(B.childNodes[A]) } }, camelize: function(A){ return A.replace(/-(.)/g, function(B, C){ return C.toUpperCase() }) }, inArray: function(A, B){ return (bkLib.search(A, B) != null) }, search: function(A, C){ for (var B = 0; B < A.length; B++) { if (A[B] == C) { return B } } return null }, cancelEvent: function(A){ A = A || window.event; if (A.preventDefault && A.stopPropagation) { A.preventDefault(); A.stopPropagation() } return false }, domLoad: [], domLoaded: function(){ if (arguments.callee.done) { return } arguments.callee.done = true; for (i = 0; i < bkLib.domLoad.length; i++) { bkLib.domLoadi } }, onDomLoaded: function(A){ this.domLoad.push(A); if (document.addEventListener) { document.addEventListener("DOMContentLoaded", bkLib.domLoaded, null) } else { if (bkLib.isMSIE) { document.write(".nicEdit-main p { margin: 0; }<\/script"); $BK("__ie_onload").onreadystatechange = function(){ if (this.readyState == "complete") { bkLib.domLoaded() } } } } window.onload = bkLib.domLoaded } }; function $BK(A){ if (typeof(A) == "string") { A = document.getElementById(A) } return (A && !A.appendTo) ? bkExtend(A, bkElement.prototype) : A } var bkEvent = { addEvent: function(A, B){ if (B) { this.eventList = this.eventList || {}; this.eventList[A] = this.eventList[A] || []; this.eventList[A].push(B) } return this }, fireEvent: function(){ var A = bkLib.toArray(arguments), C = A.shift(); if (this.eventList && this.eventList[C]) { for (var B = 0; B < this.eventList[C].length; B++) { this.eventList[C][B].apply(this, A) } } } }; function __(A){ return A } Function.prototype.closure = function(){ var A = this, B = bkLib.toArray(arguments), C = B.shift(); return function(){ if (typeof(bkLib) != "undefined") { return A.apply(C, B.concat(bkLib.toArray(arguments))) } } }; Function.prototype.closureListener = function(){ var A = this, C = bkLib.toArray(arguments), B = C.shift(); return function(E){ E = E || window.event; if (E.target) { var D = E.target } else { var D = E.srcElement } return A.apply(B, [E, D].concat(C)) } }; var nicEditorConfig = bkClass.extend({ buttons: { 'bold': { name: _('Mettre en gras'), command: 'Bold', tags: ['B', 'STRONG'], css: { 'font-weight': 'bold' }, key: 'b' }, 'italic': { name: _('Mettre en italique'), command: 'Italic', tags: ['EM', 'I'], css: { 'font-style': 'italic' }, key: 'i' }, 'underline': { name: _('Souligner'), command: 'Underline', tags: ['U'], css: { 'text-decoration': 'underline' }, key: 'u' }, 'left': { name: _('Aligné à gauche'), command: 'justifyleft', noActive: true }, 'center': { name: _('Centré'), command: 'justifycenter', noActive: true }, 'right': { name: _('Aligné à droite'), command: 'justifyright', noActive: true }, 'justify': { name: _('Justifié'), command: 'justifyfull', noActive: true }, 'ol': { name: _('Liste non ordonnée'), command: 'insertorderedlist', tags: ['OL'] }, 'ul': { name: _('Liste non ordonnée'), command: 'insertunorderedlist', tags: ['UL'] }, 'subscript': { name: _('Placer en indice'), command: 'subscript', tags: ['SUB'] }, 'superscript': { name: _('Placer en exposant'), command: 'superscript', tags: ['SUP'] }, 'strikethrough': { name: _('Barrer le texte'), command: 'strikeThrough', css: { 'text-decoration': 'line-through' } }, 'removeformat': { name: _('Supprimer la mise en forme'), command: 'removeformat', noActive: true }, 'indent': { name: _('Indenter'), command: 'indent', noActive: true }, 'outdent': { name: _('Remove Indent'), command: 'outdent', noActive: true }, 'hr': { name: _('Ligne horizontale'), command: 'insertHorizontalRule', noActive: true } }, iconsPath: 'http://js.nicedit.com/nicEditIcons-latest.gif', buttonList: ['save', 'bold', 'italic', 'underline', 'left', 'center', 'right', 'justify', 'ol', 'ul', 'fontSize', 'fontFamily', 'fontFormat', 'indent', 'outdent', 'image', 'upload', 'link', 'unlink', 'forecolor', 'bgcolor'], iconList: { "xhtml": 1, "bgcolor": 2, "forecolor": 3, "bold": 4, "center": 5, "hr": 6, "indent": 7, "italic": 8, "justify": 9, "left": 10, "ol": 11, "outdent": 12, "removeformat": 13, "right": 14, "save": 25, "strikethrough": 16, "subscript": 17, "superscript": 18, "ul": 19, "underline": 20, "image": 21, "link": 22, "unlink": 23, "close": 24, "arrow": 26, "upload": 27, "question":2 } }); ; var nicEditors = { nicPlugins: [], editors: [], registerPlugin: function(B, A){ this.nicPlugins.push({ p: B, o: A }) }, allTextAreas: function(C){ var A = document.getElementsByTagName("textarea"); for (var B = 0; B < A.length; B++) { nicEditors.editors.push(new nicEditor(C).panelInstance(A[B])) } return nicEditors.editors }, findEditor: function(C){ var B = nicEditors.editors; for (var A = 0; A < B.length; A++) { if (B[A].instanceById(C)) { return B[A].instanceById(C) } } } }; var nicEditor = bkClass.extend({ construct: function(C){ this.options = new nicEditorConfig(); bkExtend(this.options, C); this.nicInstances = new Array(); this.loadedPlugins = new Array(); var A = nicEditors.nicPlugins; for (var B = 0; B < A.length; B++) { this.loadedPlugins.push(new A[B].p(this, A[B].o)) } nicEditors.editors.push(this); bkLib.addEvent(document.body, "mousedown", this.selectCheck.closureListener(this)) }, panelInstance: function(B, C){ B = this.checkReplace($BK(B)); var A = new bkElement("DIV").setStyle({ width: (parseInt(B.getStyle("width")) || B.clientWidth) + "px" }).appendBefore(B); this.setPanel(A); return this.addInstance(B, C) }, checkReplace: function(B){ var A = nicEditors.findEditor(B); if (A) { A.removeInstance(B); A.removePanel() } return B }, addInstance: function(B, C){ B = this.checkReplace($BK(B)); if (B.contentEditable || !!window.opera) { var A = new nicEditorInstance(B, C, this) } else { var A = new nicEditorIFrameInstance(B, C, this) } this.nicInstances.push(A); return this }, removeInstance: function(C){ C = $BK(C); var B = this.nicInstances; for (var A = 0; A < B.length; A++) { if (B[A].e == C) { B[A].remove(); this.nicInstances.splice(A, 1) } } }, removePanel: function(A){ if (this.nicPanel) { this.nicPanel.remove(); this.nicPanel = null } }, instanceById: function(C){ C = $BK(C); var B = this.nicInstances; for (var A = 0; A < B.length; A++) { if (B[A].e == C) { return B[A] } } }, setPanel: function(A){ this.nicPanel = new nicEditorPanel($BK(A), this.options, this); this.fireEvent("panel", this.nicPanel); return this }, nicCommand: function(B, A){ if (this.selectedInstance) { this.selectedInstance.nicCommand(B, A) } }, getIcon: function(D, A){ var C = this.options.iconList[D]; var B = (A.iconFiles) ? A.iconFiles[D] : ""; return { backgroundImage: "url('" + ((C) ? this.options.iconsPath : B) + "')", backgroundPosition: ((C) ? ((C - 1) * -18) : 0) + "px 0px" } }, selectCheck: function(C, A){ var B = false; do { if (A.className && A.className.indexOf("nicEdit") != -1) { return false } } while (A = A.parentNode); this.fireEvent("blur", this.selectedInstance, A); this.lastSelectedInstance = this.selectedInstance; this.selectedInstance = null; return false } }); nicEditor = nicEditor.extend(bkEvent); var nicEditorInstance = bkClass.extend({ isSelected: false, construct: function(G, D, C){ this.ne = C; this.elm = this.e = G; this.options = D || {}; newX = parseInt(G.getStyle("width")) || G.clientWidth; newY = parseInt(G.getStyle("height")) || G.clientHeight; this.initialHeight = newY - 8; var H = (G.nodeName.toLowerCase() == "textarea"); if (H || this.options.hasPanel) { var B = (bkLib.isMSIE && !((typeof document.body.style.maxHeight != "undefined") && document.compatMode == "CSS1Compat")); var E = { width: newX + "px", border: "1px solid #ccc", borderTop: 0, overflowY: "auto", overflowX: "hidden" }; E[(B) ? "height" : "maxHeight"] = (this.ne.options.maxHeight) ? this.ne.options.maxHeight + "px" : null; this.editorContain = new bkElement("DIV").setStyle(E).appendBefore(G); var A = new bkElement("DIV").setStyle({ width: (newX - 8) + "px", margin: "4px", minHeight: newY + "px" }).addClass("main").appendTo(this.editorContain); G.setStyle({ display: "none" }); A.innerHTML = G.innerHTML; if (H) { A.setContent(G.value); this.copyElm = G; var F = G.parentTag("FORM"); if (F) { bkLib.addEvent(F, "submit", this.saveContent.closure(this)) } } A.setStyle((B) ? { height: newY + "px" } : { overflow: "hidden" }); this.elm = A } this.ne.addEvent("blur", this.blur.closure(this)); this.init(); this.blur() }, init: function(){ this.elm.setAttribute("contentEditable", "true"); if (this.getContent() == "") { this.setContent("") } this.instanceDoc = document.defaultView; this.elm.addEvent("mousedown", this.selected.closureListener(this)).addEvent("keypress", this.keyDown.closureListener(this)).addEvent("focus", this.selected.closure(this)).addEvent("blur", this.blur.closure(this)).addEvent("keyup", this.selected.closure(this)); this.elm.addEvent("resizestart",function(){return false}); this.elm.addEvent("dragstart",function(){return false}); this.ne.fireEvent("add", this); }, remove: function(){ this.saveContent(); if (this.copyElm || this.options.hasPanel) { this.editorContain.remove(); this.e.setStyle({ display: "block" }); this.ne.removePanel() } this.disable(); this.ne.fireEvent("remove", this) }, disable: function(){ this.elm.setAttribute("contentEditable", "false") }, getSel: function(){ return (window.getSelection) ? window.getSelection() : document.selection }, getRng: function(){ var A = this.getSel(); if (!A) { return null } return (A.rangeCount 0) ? A.getRangeAt(0) : A.createRange() }, selRng: function(A, B){ if (window.getSelection) { B.removeAllRanges(); B.addRange(A) } else { A.select() } }, selElm: function(){ var C = this.getRng(); if (C.startContainer) { var D = C.startContainer; if (C.cloneContents().childNodes.length == 1) { for (var B = 0; B < D.childNodes.length; B++) { var A = D.childNodes[B].ownerDocument.createRange(); A.selectNode(D.childNodes[B]); if (C.compareBoundaryPoints(Range.START_TO_START, A) != 1 && C.compareBoundaryPoints(Range.END_TO_END, A) != -1) { return $BK(D.childNodes[B]) } } } return $BK(D) } else { return $BK((this.getSel().type == "Control") ? C.item(0) : C.parentElement()) } }, saveRng: function(){ this.savedRange = this.getRng(); this.savedSel = this.getSel() }, restoreRng: function(){ if (this.savedRange) { this.selRng(this.savedRange, this.savedSel) } }, keyDown: function(B, A){ if (B.ctrlKey) { this.ne.fireEvent("key", this, B) } }, selected: function(C, A){ if (!A) { A = this.selElm() } if (!C.ctrlKey) { var B = this.ne.selectedInstance; if (B != this) { if (B) { this.ne.fireEvent("blur", B, A) } this.ne.selectedInstance = this; this.ne.fireEvent("focus", B, A) } this.ne.fireEvent("selected", B, A); this.isFocused = true; this.elm.addClass("selected") } return false }, blur: function(){ this.isFocused = false; this.elm.removeClass("selected") }, saveContent: function(){ if (this.copyElm || this.options.hasPanel) { this.ne.fireEvent("save", this); (this.copyElm) ? this.copyElm.value = this.getContent() : this.e.innerHTML = this.getContent() } }, getElm: function(){ return this.elm }, getContent: function(){ this.content = this.getElm().innerHTML; this.ne.fireEvent("get", this); return this.content }, setContent: function(A){ this.content = A; this.ne.fireEvent("set", this); this.elm.innerHTML = this.content }, nicCommand: function(B, A){ document.execCommand(B, false, A) } }); var nicEditorIFrameInstance = nicEditorInstance.extend({ savedStyles: [], init: function(){ var B = this.elm.innerHTML.replace(/^\s+|\s+$/g, ""); this.elm.innerHTML = ""; (!B) ? B = "" : B; this.initialContent = B; this.elmFrame = new bkElement("iframe").setAttributes({ src: "javascript:;", frameBorder: 0, allowTransparency: "true", scrolling: "no" }).setStyle({ height: "100px", width: "100%" }).addClass("frame").appendTo(this.elm); if (this.copyElm) { this.elmFrame.setStyle({ width: (this.elm.offsetWidth - 4) + "px" }) } var A = ["font-size", "font-family", "font-weight", "color"]; for (itm in A) { this.savedStyles[bkLib.camelize(itm)] = this.elm.getStyle(itm) } setTimeout(this.initFrame.closure(this), 50) }, disable: function(){ this.elm.innerHTML = this.getContent() }, initFrame: function(){ var B = $BK(this.elmFrame.contentWindow.document); B.designMode = "on"; B.open(); var A = this.ne.options.externalCSS; B.write("" + ((A) ? '' : "") + '' + this.initialContent + ""); B.close(); this.frameDoc = B; this.frameWin = $BK(this.elmFrame.contentWindow); this.frameContent = $BK(this.frameWin.document.body).setStyle(this.savedStyles); this.instanceDoc = this.frameWin.document.defaultView; this.heightUpdate(); this.frameDoc.addEvent("mousedown", this.selected.closureListener(this)).addEvent("keyup", this.heightUpdate.closureListener(this)).addEvent("keydown", this.keyDown.closureListener(this)).addEvent("keyup", this.selected.closure(this)); this.ne.fireEvent("add", this) }, getElm: function(){ return this.frameContent }, setContent: function(A){ this.content = A; this.ne.fireEvent("set", this); this.frameContent.innerHTML = this.content; this.heightUpdate() }, getSel: function(){ return (this.frameWin) ? this.frameWin.getSelection() : this.frameDoc.selection }, heightUpdate: function(){ this.elmFrame.style.height = Math.max(this.frameContent.offsetHeight, this.initialHeight) + "px" }, nicCommand: function(B, A){ this.frameDoc.execCommand(B, false, A); setTimeout(this.heightUpdate.closure(this), 100) } }); var nicEditorPanel = bkClass.extend({ construct: function(E, B, A){ this.elm = E; this.options = B; this.ne = A; this.panelButtons = new Array(); this.buttonList = bkExtend([], this.ne.options.buttonList); this.panelContain = new bkElement("DIV").setStyle({ overflow: "hidden", width: "100%", border: "1px solid #cccccc", backgroundColor: "#efefef" }).addClass("panelContain"); this.panelElm = new bkElement("DIV").setStyle({ margin: "2px", marginTop: "0px", zoom: 1, overflow: "hidden" }).addClass("panel").appendTo(this.panelContain); this.panelContain.appendTo(E); var C = this.ne.options; var D = C.buttons; for (button in D) { this.addButton(button, C, true) } this.reorder(); E.noSelect() }, addButton: function(buttonName, options, noOrder){ var button = options.buttons[buttonName]; var type = (button.type) ? eval("(typeof(" + button.type + ') == "undefined") ? null : ' + button.type + ";") : nicEditorButton; var hasButton = bkLib.inArray(this.buttonList, buttonName); if (type && (hasButton || this.ne.options.fullPanel)) { this.panelButtons.push(new type(this.panelElm, buttonName, options, this.ne)); if (!hasButton) { this.buttonList.push(buttonName) } } }, findButton: function(B){ for (var A = 0; A < this.panelButtons.length; A++) { if (this.panelButtons[A].name == B) { return this.panelButtons[A] } } }, reorder: function(){ var C = this.buttonList; for (var B = 0; B < C.length; B++) { var A = this.findButton(C[B]); if (A) { this.panelElm.appendChild(A.margin) } } }, remove: function(){ this.elm.remove() } }); var nicEditorButton = bkClass.extend({ construct: function(D, A, C, B){ this.options = C.buttons[A]; this.name = A; this.ne = B; this.elm = D; this.margin = new bkElement("DIV").setStyle({ "float": "left", marginTop: "2px" }).appendTo(D); this.contain = new bkElement("DIV").setStyle({ width: "20px", height: "20px" }).addClass("buttonContain").appendTo(this.margin); this.border = new bkElement("DIV").setStyle({ backgroundColor: "#efefef", border: "1px solid #efefef" }).appendTo(this.contain); this.button = new bkElement("DIV").setStyle({ width: "18px", height: "18px", overflow: "hidden", zoom: 1, cursor: "pointer" }).addClass("button").setStyle(this.ne.getIcon(A, C)).appendTo(this.border); this.button.addEvent("mouseover", this.hoverOn.closure(this)).addEvent("mouseout", this.hoverOff.closure(this)).addEvent("mousedown", this.mouseClick.closure(this)).noSelect(); if (!window.opera) { this.button.onmousedown = this.button.onclick = bkLib.cancelEvent } B.addEvent("selected", this.enable.closure(this)).addEvent("blur", this.disable.closure(this)).addEvent("key", this.key.closure(this)); this.disable(); this.init() }, init: function(){ }, hide: function(){ this.contain.setStyle({ display: "none" }) }, updateState: function(){ if (this.isDisabled) { this.setBg() } else { if (this.isHover) { this.setBg("hover") } else { if (this.isActive) { this.setBg("active") } else { this.setBg() } } } }, setBg: function(A){ switch (A) { case "hover": var B = { border: "1px solid #666", backgroundColor: "#ddd" }; break; case "active": var B = { border: "1px solid #666", backgroundColor: "#ccc" }; break; default: var B = { border: "1px solid #efefef", backgroundColor: "#efefef" } } this.border.setStyle(B).addClass("button-" + A) }, checkNodes: function(A){ var B = A; do { if (this.options.tags && bkLib.inArray(this.options.tags, B.nodeName)) { this.activate(); return true } } while (B = B.parentNode && B.className != "nicEdit"); B = $BK(A); while (B.nodeType == 3) { B = $BK(B.parentNode) } if (this.options.css) { for (itm in this.options.css) { if (B.getStyle(itm, this.ne.selectedInstance.instanceDoc) == this.options.css[itm]) { this.activate(); return true } } } this.deactivate(); return false }, activate: function(){ if (!this.isDisabled) { this.isActive = true; this.updateState(); this.ne.fireEvent("buttonActivate", this) } }, deactivate: function(){ this.isActive = false; this.updateState(); if (!this.isDisabled) { th

    Read the article

< Previous Page | 4 5 6 7 8